為何要用攔截器?
任何時候,如果我們想要為請求添加全局功能,例如身份認證、錯誤處理等,在請求發(fā)送給服務(wù)器之前或服務(wù)器返回時對其進行攔截,是比較好的實現(xiàn)手段。
angularJs通過攔截器提供了一個從全局層面進行處理的途徑.
攔截器允許你:
通過實現(xiàn) request 方法攔截請求: 該方法會在 $http 發(fā)送請求道后臺之前執(zhí)行,因此你可以修改配置或做其他的操作。該方法接收請求配置對象(request configuration object)作為參數(shù),然后必須返回配置對象或者 promise 。如果返回?zé)o效的配置對象或者 promise 則會被拒絕,導(dǎo)致 $http 調(diào)用失敗。
通過實現(xiàn) response 方法攔截響應(yīng): 該方法會在 $http 接收到從后臺過來的響應(yīng)之后執(zhí)行,因此你可以修改響應(yīng)或做其他操作。該方法接收響應(yīng)對象(response object)作為參數(shù),然后必須返回響應(yīng)對象或者 promise。響應(yīng)對象包括了請求配置(request configuration),頭(headers),狀態(tài)(status)和從后臺過來的數(shù)據(jù)(data)。如果返回?zé)o效的響應(yīng)對象或者 promise 會被拒絕,導(dǎo)致$http 調(diào)用失敗。
通過實現(xiàn) requestError 方法攔截請求異常: 有時候一個請求發(fā)送失敗或者被攔截器拒絕了。請求異常攔截器會俘獲那些被上一個請求攔截器中斷的請求。它可以用來恢復(fù)請求或者有時可以用來撤銷請求之前所做的配置,比如說關(guān)閉進度條,激活按鈕和輸入框什么之類的。
通過實現(xiàn) responseError 方法攔截響應(yīng)異常: 有時候我們后臺調(diào)用失敗了。也有可能它被一個請求攔截器拒絕了,或者被上一個響應(yīng)攔截器中斷了。在這種情況下,響應(yīng)異常攔截器可以幫助我們恢復(fù)后臺調(diào)用。
攔截器的核心是服務(wù)工廠,通過向$httpprovider.interceptors數(shù)組中添加服務(wù)工廠。在$httpProvider中進行注冊。
angularJs提供四種攔截器,其中兩種成功攔截器(request、response),兩種失敗攔截器(requestError、responseError)。
在服務(wù)中添加一種或多種攔截器:
angular.module("myApp", []) .factory('httpInterceptor', [ '$q', '$injector',function($q, $injector) { var httpInterceptor = { 'responseError' : function(response) { ...... return $q.reject(response); }, 'response' : function(response) { ...... return response; }, 'request' : function(config) { ...... return config; }, 'requestError' : function(config){ ...... return $q.reject(config); } } return httpInterceptor; } 然后使用$httpProvider在.config()函數(shù)中注冊攔截器
angular.module("myApp", []) .config([ '$httpProvider', function($httpProvider) { $httpProvider.interceptors.push('httpInterceptor'); } ]); 實際的例子:(對401、404的攔截)
routerApp.config([ '$httpProvider', function($httpProvider) { $httpProvider.interceptors.push('httpInterceptor'); } ]); routerApp.factory('httpInterceptor', [ '$q', '$injector',function($q, $injector) { var httpInterceptor = { '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) { alert("404!"); return $q.reject(response); } }, 'response' : function(response) { return response; } } return httpInterceptor; } ]); Session 注入(請求攔截器)
這里有兩種方式來實現(xiàn)服務(wù)端的認證。第一種是傳統(tǒng)的 Cookie-Based 驗證。通過服務(wù)端的 cookies 來對每個請求的用戶進行認證。另一種方式是 Token-Based 驗證。當(dāng)用戶登錄時,他會從后臺拿到一個 sessionToken。sessionToken 在服務(wù)端標(biāo)識了每個用戶,并且會包含在發(fā)送到服務(wù)端的每個請求中。
下面的 sessionInjector 為每個被俘獲的請求添加了 x-session-token 頭 (如果當(dāng)前用戶已登錄):
<!-- lang: js -->module.factory('sessionInjector', ['SessionService', function(SessionService) { var sessionInjector = { request: function(config) { if (!SessionService.isAnonymus) { config.headers['x-session-token'] = SessionService.token; } return config; } }; return sessionInjector;}]);module.config(['$httpProvider', function($httpProvider) { $httpProvider.interceptors.push('sessionInjector');}]);然后創(chuàng)建一個請求:
<!-- lang: js -->$http.get('https://api.github.com/users/naorye/repos');被 sessionInjector 攔截之前的配置對象是這樣的:
<!-- lang: js -->{ "transformRequest": [ null ], "transformResponse": [ null ], "method": "GET", "url": "https://api.github.com/users/naorye/repos", "headers": { "Accept": "application/json, text/plain, */*" }}被 sessionInjector 攔截之后的配置對象是這樣的:
<!-- lang: js -->{ "transformRequest": [ null ], "transformResponse": [ null ], "method": "GET", "url": "https://api.github.com/users/naorye/repos", "headers": { "Accept": "application/json, text/plain, */*", "x-session-token": 415954427904 }}以上內(nèi)容給大家介紹了AngularJs HTTP響應(yīng)攔截器的相關(guān)知識,希望本文分享能夠給大家?guī)韼椭?/p>
新聞熱點
疑難解答