0

エラーをキャプチャしている間にアプリケーションの応答エラーをキャプチャしています。通知アラートサービスがコントローラのtypeErrorを取得できません:未定義のプロパティ 'アラート'を読み取ることができません

インターセプタでは、レスポンスコードに従って、rootscopeブロードキャストを割り当てて、コントローラにアラートメッセージを表示します。 ここに$ rootScope。$ブロードキャスト( 'loginRequired');インターセプターで割り当て中で、コントローラー内でサービス応答でキャプチャーしています。

$rootScope.$on("loginRequired", function(e) { 
    alert("hello"); 
    alertsManager.addAlert('Yay!', 'alert-success'); 
}); 

インターセプタ。コントローラで

var interceptor = function($q, alerts, $rootScope, $timeout, $location) { 
    return { 
    request: function(config) { 
     console.log(config); 
     return config; 
    }, 
    response: function(response) { 
     var deferred = $q.defer(); 
     $rootScope.$broadcast('loginRequired'); 
     return response || $q.when(response); 
    }, 
    responseError: function(rejection) { 
     if (rejection.status == 500) { 
     $location.url('/ho'); 
     var deferred = $q.defer(); 
     $rootScope.$broadcast('loginRequired'); 
     return $q.reject(rejection); 
     } 
     console.log(rejection.status); 
     return $q.reject(rejection); 
    } 
    } 
}; 

$httpProvider.interceptors.push(interceptor); 

alertManagerfactory

var alertsManager = function() { 
    return { 
    alerts: {}, 
    addAlert: function(message, type) { 
     this.alerts[type] = this.alerts[type] || []; 
     this.alerts[type].push(message); 
    }, 
    clearAlerts: function() { 
     for (var x in this.alerts) { 
     delete this.alerts[x]; 
     } 
    } 
    }; 
}; 
alertsManager.$inject = []; 

:コントローラビューで

var LoginController = function($scope, $rootScope, alerts, alertsManager) { 

    $scope.alerts = alertsManager.alerts; 
    // getting error in this line 
    //getting typeError: Cannot read property 'alerts' of undefined 

    LoginService.AfterLogin(username, password) 
    .then(function(response) {}, function(status) { 
     console.log("Error" + status); 
     if (status === 500) { 
     $rootScope.$on("loginRequired", function(e) { 
      alert("hello"); 
      alertsManager.addAlert('Yay!', 'alert-success'); 
     }); 
     } 
    }); 
}; 
LoginController.$inject = ['$scope', '$rootScope', 'alerts', 'alertsManager']; 

<div ng-repeat="alert in alerts" ng-class="'alert-' + (alert.type || 'warning')" close="closeAlert($index)">{{alert.msg}}</div> 

答えて

0

あなたaddAlert「方法」で「この」キーワードは、実際にあなたがaddAlertプロップに割り当てた無名関数を参照しています。

これに対処する方法はいくつかあります。たとえば、オブジェクトを保持する変数を作成します。

var alertsManager = function() { 
    var $this = { 
    alerts: {}, 
    addAlert: function(message, type) { 
     $this.alerts[type] = $this.alerts[type] || []; 
     $this.alerts[type].push(message); 
    }, 
    clearAlerts: function() { 
     for (var x in $this.alerts) { 
     delete $this.alerts[x]; 
     } 
    } 
    }; 
    return $this; 
}; 
alertsManager.$inject = []; 
関連する問題