angular 用拦截器统一处理http请求和响应的方法
更新时间:2017年06月08日 08:09:14 投稿:jingxian
下面小编就为大家带来一篇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) {
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);
}])
以上这篇angular 用拦截器统一处理http请求和响应的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持脚本之家。
您可能感兴趣的文章:
相关文章
angular.js指令中transclude选项及ng-transclude指令详解
这篇文章主要研究一下如何使用ng-transclude指令,以及指令的transclude选项的相关资料,文中介绍的非常详细,并给出了完整的示例代码大家参考学习,需要的朋友们下面来一起看看吧。2017-05-05
Angular.js与Bootstrap相结合实现表格分页代码
最近一直在学习angularjs相关知识,在学习过程中写了一个小demo,下面把代码思路分享给大家,感兴趣的朋友一起学习2016-04-04
详解JavaScript的AngularJS框架中的表达式与指令
这篇文章主要介绍了JavaScript的AngularJS框架中的表达式与指令,文中罗列了几个常用的指令属性加以说明,需要的朋友可以参考下2016-03-03


最新评论