将$ http服务注入$ http拦截器?

时间:2015-09-04 16:37:35

标签: javascript angularjs dependency-injection circular-dependency service-locator

我有以下拦截器:

var interceptor = ['$http', '$q', function ($http, $q) {
     //...
}];

这会生成循环依赖,因为$http依赖于此拦截器,此拦截器将依赖于$http

我想获得$http服务,因为如果我收到 401 Unauthorized 响应,我打算刷新用户的一些授权令牌。

为此,我必须调用我的OAuth端点并检索新的令牌。

如何将此服务注入我的拦截器?

我也尝试了以下替代方案:

var interceptor = ['$injector', '$q', function ($injector, $q) {
     var $http = $injector.get('$http');
}]

但是我得到了同样的错误。

这可能吗?

我不想使用jQuery库,我希望我的应用程序是纯粹的AngularJS,所以$.ajax(...)答案对我没用。

2 个答案:

答案 0 :(得分:2)

即使是第二个片段也会导致cdep错误,因为拦截器服务将被实例化,并且在构造函数中,您尝试在此过程中获取$http,这会导致cdep错误。在实例化拦截器服务之后,您需要稍后获取http服务(或任何注入http的服务)。您可以根据需要轻松地从$injector获取,例如reponseError

var interceptor = ['$injector', '$q',
    function($injector, $q) {
      return {

        responseError: function(rejection) {
          //Get it on demand or cache it to another variable once you get it. But you dont really need to do that you could get from the injector itself since it is not expensive as service is a singleton.
          var $http = $injector.get('$http');
          //Do something with $http
          return $q.reject(rejection);
        }
      }
    }
  ]

答案 1 :(得分:-1)

尝试使用匿名函数

包装您的注入器代码
  var interceptor = ['$injector', '$q', function ($injector, $q) {
          return function(){
                var $http = $injector.get('$http');
          }
  }];
相关问题