问题是将$ rootScope注入到Angular的配置中?

时间:2015-02-10 16:31:13

标签: angularjs

我在做:

myApp.config([
  '$httpProvider', '$rootScope', function($httpProvider, $rootScope) {
    $httpProvider.interceptors.push(function($q) {
      return {
        responseError: function(rejection) {
          var defer;
          defer = $q.defer();
          if (rejection.status === 401) {
            $rootScope.$broadcast('api-error', rejection);
          }
          defer.reject(rejection);
          return defer.promise;
        },
        response: function(response) {
          var defer;
          defer = $q.defer();
          console.log(response);
          if (response.status === 401) {
            $rootScope.$broadcast('api-error', response);
            defer.reject(response);
          } else {
            defer.resolve(response);
          }
          return defer.promise;
        }
      };
    });
  }
]);

但我收到错误,找不到$rootScope。我读了this answer,它说要做一些奇怪的全局变量,这看起来是个坏主意。 那么如何在401状态下重定向到另一条路线?

1 个答案:

答案 0 :(得分:13)

在拦截器中注入$rootScope,而不是在配置函数中注入:

myApp.config([
  '$httpProvider', function($httpProvider) {
    $httpProvider.interceptors.push(function($q, $rootScope) {
     ...