標籤:mod [] console angularjs code provider ade response tor
想使用angularjs裡的htpp向後台發送請求,現在有個使用者唯一識別的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);}])
angularjs http設定headers (使用者唯一識別 token )