在$http拦截器中注入$http服务

Injecting $http service into $http interceptor?

本文关键字:http 注入 服务      更新时间:2023-09-26

我有以下拦截器:

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(...)答案对我没用。

甚至第二个片段也会导致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);
        }
      }
    }
  ]

尝试用匿名函数包装你的注入器代码

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