通知警报服务无法在控制器中获取typeError:无法读取未定义

时间:2016-12-28 08:04:50

标签: angularjs angularjs-directive angularjs-scope angular-ui-router

我捕获应用程序响应错误,同时捕获错误,我收到错误。

在Interceptor中,根据响应代码,分配了rootscope广播并在控制器中显示警报消息。 这里$ 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>

1 个答案:

答案 0 :(得分:0)

&#34;这&#34;你的addAlert&#34;方法&#34;中的关键字实际上是引用你已经分配给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 = [];