当前位置 : 首页 » 编程语言 » 正文

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

分类 : 编程语言 | 发布时间 : 2018-04-21 09:06:21 | 浏览 : 13

想使用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);
}])

相关阅读:

Remove duplicates from an array of objects in JavaScript

Can I call jquery click() to follow an <a> link if I haven't bound an event handler to it with bind or click already?

Check whether a string matches a regex in JS

jQuery event to trigger action when a div is made visible

Check if user is using IE with jQuery

Resize HTML5 canvas to fit window

How do I replace a character at a particular index in JavaScript?

JavaScript file upload size validation

Converting a string to a date in JavaScript

How to get the data-id attribute?