angular 用拦截器统一处理http请求和响应的方法
想使用angularjs里的htpp向后台发送请求,现在有个用户唯一识别的token想要放到headers里面去,也就是{headres:{'token':1}}
index.html里引入以下js:
angular.module('app.factorys',[])
.factory('httpInterceptor',['$q','$injector','$localStorage',function($q,$injector,$localStorage){
varhttpInterceptor={
'responseError':function(response){
//......
return$q.reject(response);
},
'response':function(response){
if(response.status==21000){
//console.log('dosomething...');
}
returnresponse||$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;
};
returnconfig||$q.when(config);
returnconfig;
},
'requestError':function(config){
//......
return$q.reject(config);
}
};
returnhttpInterceptor;
}])
在app里注入factory后,在config里面配置
.config(['$httpProvider',function(){
$httpProvider.interceptors.push(httpInterceptor);
}])
以上这篇angular用拦截器统一处理http请求和响应的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持毛票票。
热门推荐
1 训练狗狗憋尿
2 狗狗追踪训练
3 狗狗训练要多少钱
5 深圳狗狗训练
6 训练狗狗唤回
7 狗狗叫怎么训练
8 狗狗训练班
10 狗狗社会化训练
11 狗狗叫回训练
12 广州狗狗训练学校
13 狗狗训练躺下
14 狗狗随行训练
15 训练狗狗巡回
16 狗狗要怎么训练
17 狗狗喂食训练
18 训练狗狗躺下