简体   繁体   English

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

[英]Injecting $http service into $http interceptor?

I have the following interceptor: 我有以下拦截器:

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

This generates a circular dependency , because $http will depend on this interceptor, and this interceptor will depend on $http . 这将产生循环依赖关系 ,因为$http将依赖于此拦截器,而此拦截器将取决于$http

I want to get the $http service because I intend to refresh some authorization tokens of the user if I get a 401 Unauthorized response. 我想获得$http服务,因为如果收到401未经授权的响应,我打算刷新用户的一些授权令牌。

For this, I have to call my OAuth endpoint and retrieve the new tokens. 为此,我必须调用OAuth端点并检索新令牌。

How can I inject this service into my interceptor? 如何将该服务注入拦截器?

I also tried the following alternative: 我还尝试了以下替代方法:

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

But I'm getting the same error. 但是我遇到了同样的错误。

Is this possible? 这可能吗?

I don't want to use the jQuery library and I want my application to be pure AngularJS, so $.ajax(...) answers are not useful to me. 我不想使用jQuery库,我希望我的应用程序是纯AngularJS,因此$.ajax(...)答案对我没有用。

Even the second snippet causes cdep error because interceptor service will get instantiated and in the constructor you are trying to get $http in the process, which causes cdep error. 即使第二个代码段也会导致cdep错误,因为拦截器服务将被实例化,并且在构造函数中,您尝试在此过程中获取$http ,这会导致cdep错误。 You would need to get the http service (or any of your service that injects http) later, after interceptor service has been instantiated. 在拦截器服务实例化之后,您将需要稍后获得http服务(或任何注入http的服务)。 You could easily get it from $injector on demand when you need it, example on a reponseError . 您可以根据需要从$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);
        }
      }
    }
  ]

try wrapping your injector code with in anonymous function 尝试在匿名函数中包装您的注射器代码

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM