[英]How to intercept every Ajax Request with Angular JS
我需要攔截每個Ajax請求,以驗證服務器是否以401 Unauthorized
響應,因為會話已過期並重定向到登錄頁面,因此用戶不認為該應用程序停止工作。 我可以使用JQuery通過以下方式執行此操作:
$( document ).ajaxComplete(function( event, xhr, settings ) {
if(xhr.errorCode == 401 || xhr.responseText === "unauthorized") {
location.href = "/Login";
}
});
如何使用Angular JS做到這一點?
您可以在應用程序config()上設置$ interceptor
.config(['$httpProvider', function($httpProvider) {
$httpProvider.interceptors.push(['$location', '$q', function($location, $q) {
return {
'request': function(request) {
return request;
},
'responseError': function(response) {
if (response.status === 401) {
// do stuff
}
// otherwise, default behaviour
return $q.reject(response);
}
};
}]);
}])
使用httpInterceptor
。 不久前回答了非常類似的問題。 然后,您應該對'response'
hanndler感興趣,並在其中添加您的特定邏輯。
制作一個用於進行所有調用的函數,您只需要在一個地方處理錯誤,而不是多個地方
function makeCall(obj, cb) {
$http({
method: obj.method,
url: obj.url,
data: obj.data || {}
}, function(res) {
// non error statuses get handled here
}, function(res) {
// error statuses get handled here
})
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.