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

Injecting $http service into $http interceptor?

我有以下拦截器:

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

这会产生一个循环依赖,因为$http会依赖这个拦截器,而这个拦截器又会依赖$http.

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

为此,我必须调用我的 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');
          }
  }];