1

我有以下拦截器:

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

+0

包裹你的喷油器的代码也许你可以激发关闭事件或调用另一个服务做的工作适合你? – JoseM

回答

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

尝试用匿名函数

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