0

在Angular js中真的找不到有關http攔截器的好文檔。雖然通過ng-include致毒處理錯誤,我可以利用這個攔截responseError

app.config(function ($httpProvider) { 
    $httpProvider.interceptors.push('templateInterceptor'); 
}); 

// register the interceptor as a service 
app.factory('templateInterceptor', function($q) { 
    return { 
    'responseError': function(rejection) { 
     var isTemplate = !!rejection.config.url.match(/^content/g); 
     if (isTemplate) { 
     // here we add error message, but how this message appesrs in the place of ng-include 
     rejection.data = '<div><template-error url="\''+ (rejection.config.url) + '\'"><strong>Error from interceptor.</strong></template-error></div>'; 
     return rejection; 
     } else { 
     return $q.reject(rejection); 
     } 
    } 
    } 
}); 

此代碼從這個問題how to catch angular ng-include error拍攝。 我不明白,攔截器是如何工作的?他們必須返回什麼?如何使用rejection傳遞給responseError攔截器的參數?在rejectiondata屬性用於包含錯誤消息到失敗ng-include指令的地方,這是如何工作的?

+0

你看過https://docs.angularjs.org/api/ng/service/$http#interceptors – 2014-10-26 19:04:36

回答

1

如果有來電$http,如

$http(....).then(function(results) { 
    // Success callback 
}, function(error) { 
    // Error callback 
}); 

服務器用一個錯誤響應,那麼responseError攔截器將獲得運行成功或錯誤回調之前調用。

  • 如果最後的攔截返回不答應,然後從視圖調用代碼的角度任意值,調用$http是成功的,成功的回調將被執行,通過在返回值作爲results參數

  • 如果最後的攔截返回得到一個值解決的承諾,那麼類似上面的情況,從調用代碼的角度來看,調用$http是成功的,而成功回調將被執行,傳入已解析的值作爲results參數。

  • 如果最後的攔截返回被拒絕,一個錯誤的諾言,那麼從視圖調用代碼的點,調用$http成功,錯誤回調將被執行,傳遞被拒絕的錯誤爲error參數。

ngInclude指令將注入頁面從成功調用$http的結果data關鍵。 https://stackoverflow.com/a/20838764/1319998的代碼會將錯誤的電話號碼從ngInclude轉換爲$http,成功執行,並將錯誤消息的html作爲結果中的data鍵。