您好,登錄后才能下訂單哦!
這篇文章給大家分享的是有關(guān)angular如何使用攔截器統(tǒng)一處理http請求和響應(yīng)的內(nèi)容。小編覺得挺實用的,因此分享給大家做個參考,一起跟隨小編過來看看吧。
想使用angularjs里的htpp向后臺發(fā)送請求,現(xiàn)在有個用戶唯一識別的token想要放到headers里面去,也就是{headres:{'token':1}}
index.html里引入以下js:
angular.module('app.factorys',[]) .factory('httpInterceptor',['$q','$injector','$localStorage',function ($q,$injector,$localStorage) { var httpInterceptor = { 'responseError' : function(response) { // ...... return $q.reject(response); }, 'response' : function(response) { if (response.status == 21000) { // console.log('do something...'); } return response || $q.when(response); }, 'request' : function(config) { config.headers = config.headers || {}; if ($localStorage.token) { config.headers.token = $localStorage.token; // config.headers['X-Access-Token'] = $localStorage.token; }; return config || $q.when(config); return config; }, 'requestError' : function(config){ // ...... return $q.reject(config); } }; return httpInterceptor; }])
在app里注入factory后,在config里面配置
.config(['$httpProvider',function(){ $httpProvider.interceptors.push(httpInterceptor); }])
感謝各位的閱讀!關(guān)于“angular如何使用攔截器統(tǒng)一處理http請求和響應(yīng)”這篇文章就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,讓大家可以學(xué)到更多知識,如果覺得文章不錯,可以把它分享出去讓更多的人看到吧!
免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。