简体   繁体   English

在$ http拦截器中重新调用$ http请求

[英]Reinvoke $http request in $http interceptor

So I am intercepting an angular $http request and response. 因此,我截取了有角度的$ http请求和响应。 Lets say that if I had a response error, I want to reinvoke my $http call. 可以说,如果发生响应错误,我想重新调用$ http调用。 The issue is that I need to inject $http service into my interceptor and it creates a circular dependency. 问题是我需要将$ http服务注入到我的拦截器中,并创建一个循环依赖项。 This is the simplified version of my code in coffeescript: 这是我在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');
]

Thanks 谢谢

To avoid the circular dependency you could always just decorate the $http service to handle this functionality. 为了避免循环依赖,您始终可以只装饰$http服务来处理此功能。 Here is an example of a decorator. 这是装饰器的示例

You would basically do something like this pseudocode: 您基本上会执行类似以下伪代码的操作:

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;

This basically wraps the original $http call in your retry functionality. 这基本上将原始的$ http调用包装在您的重试功能中。 The code is untested as it's just a basic idea of how to do it. 该代码未经测试,因为它只是如何执行此操作的基本概念。 Also you should be careful, since this could create an infinite loop. 另外,您还应小心,因为这可能会导致无限循环。

Hope this helps! 希望这可以帮助!

After reviewing the Angular source code the better answer is such. 查看Angular源代码后,更好的答案就是这样。 $http method is accessible without dependency injection so the trick is to NOT INJECT $http and to simply use it. $ http方法无需依赖项注入即可访问,因此诀窍是不要注入$ http并简单地使用它。 Like such: 像这样:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM