在$http拦截器中注入$http服务
Injecting $http service into $http interceptor?
我有以下拦截器:
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');
}
}];
相关文章:
- 使用Objective-C的JavaScript注入方法
- Meteor如何接收HTTP请求
- 正在注入包含JS的HTML
- 迷你$provider注入茉莉花和角
- Angularjs工厂注入错误
- angularjs自定义模块与$http注入
- javascript注入$http-post方法不起作用
- 如何在没有打字稿的情况下在 Angular 2 中注入 Http
- 尽管注入了$http,但它在服务中是未定义的
- Ionic 2-导入/注入Angular 2 HTTP组件
- 注入$http在使用typescript的jasmine测试中失败
- 错误:将Angular$http服务注入需要插件
- 即使在注入http之后,Uncaught TypeError: Cannot read property 'ge
- 注入和使用Http
- 无法使用AngularJS显式注入' $http '.控制器的语法
- 在$http拦截器中注入$http服务
- 使用$http注入的自定义指令
- 如何在一条注入语句中注入$scope、$http、$q、$location这四个变量
- 如何将自定义HTTP标头注入SuperAgent发出的每个请求中
- 将$http注入angular“;使用严格的“;服务