【轉】AngularJs HTTP請求響應攔截器


任何時候,如果我們想要為請求添加全局功能,例如身份認證、錯誤處理等,在請求發送給服務器之前或服務器返回時對其進行攔截,是比較好的實現手段。

angularJs通過攔截器提供了一個從全局層面進行處理的途徑。

四種攔截器

實現 request 方法攔截請求

request: function(config) {
// do something on request success
return config || $q.when(config);
}

該方法會在 $http 發送請求后台之前執行,因此你可以修改配置或做其他的操作。該方法接收請求配置對象(request configuration object)作為參數,然后必須返回配置對象或者 promise 。如果返回無效的配置對象或者 promise 則會被拒絕,導致 $http 調用失敗。

實現 requestError 方法攔截請求異常

requestError: function(rejection) {
  // do something on request error  return $q.reject(rejection);
}

有時候一個請求發送失敗或者被攔截器拒絕了,請求異常攔截器會俘獲那些被上一個請求攔截器中斷的請求。它可以用來恢復請求或者有時可以用來撤銷請求之前所做的配置,比如說關閉進度條,激活按鈕和輸入框什么之類的。

實現 response 方法攔截響應

response: function(response) {
  // do something on response success
return response || $q.when(response);}

該方法會在 $http 接收到從后台過來的響應之后執行,因此你可以修改響應或做其他操作。該方法接收響應對象(response object)作為參數,然后必須返回響應對象或者 promise。響應對象包括了請求配置(request configuration),頭(headers),狀態(status)和從后台過來的數據(data)。如果返回無效的響應對象或者 promise 會被拒絕,導致$http 調用失敗。

實現 responseError 方法攔截響應異常

responseError: function(rejection) {
// do something on response error  return $q.reject(rejection);
}

有時候我們后台調用失敗了,也有可能它被一個請求攔截器拒絕了或者被上一個響應攔截器中斷了。在這種情況下,響應異常攔截器可以幫助我們恢復后台調用。

攔截器核心

攔截服務工廠

var app = angular.module("ajaxHttp", []);
app.factory("httpInterceptor", [ "$q", "$rootScope", function($q, $rootScope) {
return {
request: function(config) {
// do something on request success
return config || $q.when(config);
},
   requestError: function(rejection) {
     // do something on request error
     return $q.reject(rejection)
   },
response: function(response) {
// do something on response success
return response || $q.when(response);
},
responseError : function(rejection) {
// do something on response error
return $q.reject(rejection);
}
};
}]);

注冊攔截工廠方法

app.config(["$httpProvider", function($httpProvider) {
  $httpProvider.interceptors.push("httpInterceptor");
}]);

示例

對401,404的攔截處理

app.config(["$httpProvider", function($httpProvider) { 
$httpProvider.interceptors.push('httpInterceptor'); 
}]); 
app.factory("httpInterceptor", ["$q", "$injector", function($q, $injector) {
return {
"responseError": function(response) {
if (response.status == 401) {
var rootScope = $injector.get('$rootScope');
var state = $injector.get('$rootScope').$state.current.name;
rootScope.stateBeforLogin = state;
rootScope.$state.go("login");
return $q.reject(response);
}
else if (response.status === 404) {
console.log("404!");
return $q.reject(response);
}
}
};
]);

原文地址:http://www.jb51.net/article/77318.htm


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM