与重试$ HTTP请求拦截器 [英] Retry request with $http interceptor
问题描述
我敢肯定有一个简单的方法做我想做的,我只是不能换我的头周围。我怎样才能在角的HTTP拦截如果失败重试的请求?我想我会建立某种请求权的承诺?然后在回应我会检查响应是否是一个错误,如果是的话,做的承诺?这是怎么一回事?我一直在努力适应这里的例子: http://docs.angularjs.org/api/ng.$http
I'm sure there is an easy way to do what I want, I just cant wrap my head around it. How can I get the http interceptor in angular to retry a request if it fails? I imagine I would have to build some sort of promise in the request right? Then in the response I would have to check whether the response was an error and if so, do the promise? How is that done? I have been trying to adapt the example here: http://docs.angularjs.org/api/ng.$http
我试图使用拦截器的原因是因为我需要添加标记和其他一些东西到请求的URL,以及一些事情要处理XDR的。
The reason I am trying to use an interceptor is because I need to add the token and a few other things to the request url, as well as some things to handle xdr's.
推荐答案
下面是一个HTTP $该拦截器(立即)重播超时请求(S)(即响应状态0)。有两个非显而易见性(我!)元素来构建这个例子:
Here's a $http interceptor that (immediately) replays timed out request(s) (i.e. response status 0). There were two non-obvious (to me!) elements to constructing this example:
- 如何调用$ HTTP从拦截中 - 简单地增加$ HTTP到依赖关系清单没有工作的角度循环依赖的抱怨
- 如何从响应对象引用原始的请求,以重试
这个答案解决这两个议题,但更多地参与,所以我下面包括一个简化版本。
This answer addresses both topics but is more involved so I include a simplified version below.
joinApp.factory('httpResponseErrorInterceptor',function($q, $injector) {
return {
'responseError': function(response) {
if (response.status === 0) {
// should retry
var $http = $injector.get('$http');
return $http(response.config);
}
// give up
return $q.reject(response);
}
};
});
joinApp.config(function($httpProvider) {
$httpProvider.interceptors.push('httpResponseErrorInterceptor');
});
在实际实施中,你可能会想要更复杂的HTTP响应code处理,一个极限的时候,你再试一次,数量等。
In your actual implementation, you would likely want more sophisticated http response code processing, a limit to the number of times you retry, etc.
这篇关于与重试$ HTTP请求拦截器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!