繁体   English   中英

将$ 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');
          }
  }];

暂无
暂无

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

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