簡體   English   中英

在$ http攔截器中重新調用$ http請求

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM