使用 $http 拦截器重试请求 [英] Retry request with $http interceptor
问题描述
我确信有一种简单的方法可以做我想做的事,我只是无法理解它.如果请求失败,如何以 angular 获取 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 拦截器,它(立即)重放超时请求(即响应状态 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 添加到依赖项列表中是行不通的,因为 angular 抱怨循环依赖项
- 如何从响应对象引用原始请求以便重试
这个答案解决了这两个主题,但涉及更多,所以我在下面提供了一个简化版本.
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 响应代码处理、重试次数限制等.
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屋!