国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > JavaScript > 正文

快速學習AngularJs HTTP響應攔截器

2019-11-20 10:53:05
字體:
來源:轉載
供稿:網友

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

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

四種攔截器

實現 request 方法攔截請求

request: function(config) {// do something on request successreturn 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 successreturn 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 successreturn config || $q.when(config);},   requestError: function(rejection) {     // do something on request error     return $q.reject(rejection)   },response: function(response) {// do something on response successreturn response || $q.when(response);},responseError : function(rejection) {// do something on response errorreturn $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);}}};]);

以上內容給大家分享快速學習AngularJs HTTP響應攔截器 的相關知識,希望大家喜歡,同時感謝大家一直以來對武林網網站的支持。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 潼关县| 芒康县| 克拉玛依市| 平陆县| 陆丰市| 黄浦区| 苗栗市| 达州市| 左贡县| 阳江市| 桃园市| 娱乐| 青铜峡市| 托里县| 漳浦县| 沧州市| 景洪市| 苍山县| 濮阳县| 陆丰市| 河津市| 墨竹工卡县| 宕昌县| 兖州市| 磐石市| 开远市| 兴和县| 淳安县| 榆社县| 沧源| 紫阳县| 阳原县| 瓦房店市| 双江| 全南县| 出国| 淳化县| 泽普县| 龙口市| 保康县| 额济纳旗|