微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

angular 用拦截器统一处理http请求和响应的方法

想使用angularjs里的htpp向后台发送请求,现在有个用户唯一识别的token想要放到headers里面去,也就是{headres:{'token':1}}

index.html里引入以下js:

rush:xhtml;"> 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 con<a href="https://www.jb51.cc/tag/fig/" target="_blank" class="keywords">fig</a> || $q.when(con<a href="https://www.jb51.cc/tag/fig/" target="_blank" class="keywords">fig</a>);

    return con<a href="https://www.jb51.cc/tag/fig/" target="_blank" class="keywords">fig</a>;
  },'requestError' : function(con<a href="https://www.jb51.cc/tag/fig/" target="_blank" class="keywords">fig</a>){
    // ......
    return $q.reject(con<a href="https://www.jb51.cc/tag/fig/" target="_blank" class="keywords">fig</a>);
  }
};
return httpInterceptor;

}])

在app里注入factory后,在config里面配置

rush:xhtml;"> .config(['$httpProvider',function(){ $httpProvider.interceptors.push(httpInterceptor); }])

以上这篇angular 用拦截器统一处理http请求和响应的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持编程之家。

原文地址:https://www.jb51.cc/js/38783.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐