[英]Reinvoke $http request in $http interceptor
因此,我截取了有角度的$ http请求和响应。 可以说,如果发生响应错误,我想重新调用$ http调用。 问题是我需要将$ http服务注入到我的拦截器中,并创建一个循环依赖项。 这是我在coffeescript中的代码的简化版本:
retryModule = angular.module('retry-call', [])
retryModule.factory 'RetryCall', ($q, $http)->
# More object keys
'responseError': (response)=>
# Retry request if failed
# I need a different way of invoking $http() to avoid circular dependency
$http(response.config)
$q.reject(response)
retryModule.config ['$httpProvider', ($httpProvider)->
$httpProvider.interceptors.push('RetryCall');
]
谢谢
为了避免循环依赖,您始终可以只装饰$http
服务来处理此功能。 这是装饰器的示例 。
您基本上会执行类似以下伪代码的操作:
var old_post = $delegate.post;
$delegate.post = function(post_stuff) {
var def = $q.defer();
old_post(post_stuff).then(function(data) {
if (data.error) {
$delegate.post(post_stuff).then(function(data) {
def.resolve(data);
}
} else {
def.resolve(data)
}
}, function(err_data) {
// Also retry here
});
};
return $delegate;
这基本上将原始的$ http调用包装在您的重试功能中。 该代码未经测试,因为它只是如何执行此操作的基本概念。 另外,您还应小心,因为这可能会导致无限循环。
希望这可以帮助!
查看Angular源代码后,更好的答案就是这样。 $ http方法无需依赖项注入即可访问,因此诀窍是不要注入$ http并简单地使用它。 像这样:
Right Way
retryModule = angular.module('retry-call', [])
# Do not inject $http
retryModule.factory 'RetryCall', ($q)->
# More object keys
'responseError': (response)=>
# Just use $http without injecting it
$http(response.config)
$q.reject(response)
retryModule.config ['$httpProvider', ($httpProvider)->
$httpProvider.interceptors.push('RetryCall');
]
Wrong Way
# Do not do it this way.
retryModule.factory 'RetryCall', ($q,$http)->
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.