0

我捕获应用程序响应错误,同时捕获错误,我收到错误。通知警报服务无法在控制器获取typeError:无法读取未定义的属性'警报'

在拦截器中,根据响应代码,在控制器中分配rootcope广播并显示警报消息。 这里$ rootScope。$ broadcast('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“method”中的“this”关键字实际上是引用了您分配给addAlert prop的匿名函数。

有几种方法可以解决这个问题。例如创建包含您的对象的变量。

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 = []; 
相关问题