我刚刚使用AngularJS构建了我的第一个Yeoman应用程序。我这样做是这样的:

$ yo angular frontend


结果,我得到了一堆标准文件夹和文件,例如:

- app
    - images
    - scripts
        app.js
    - styles
    - views
    index.html
    ...
- bower_components
- node_modules
- test


似乎我必须更改app.js文件才能向所有请求添加标头。但是我对AngularJs还是陌生的,我不知道该怎么做。现在,app.js看起来像:

angular
    .module('frontend', [
        ...
    ])
    .config(function($routeProvider){
        $routeProvider
            .when(...)
    });


我想我需要设置$httpProvider,但是我该怎么做呢?

最佳答案

您应该为此使用interceptor。这是来自AngularJS文档的推荐方法:

// register the interceptor as a service
$provide.factory('myHttpInterceptor', function($q, dependency1, dependency2) {
  return {
    // optional method
    'request': function(config) {
      // do something on success
      return config;
    },

    // optional method
   'requestError': function(rejection) {
      // do something on error
      if (canRecover(rejection)) {
        return responseOrNewPromise
      }
      return $q.reject(rejection);
    },



    // optional method
    'response': function(response) {
      // do something on success
      return response;
    },

    // optional method
   'responseError': function(rejection) {
      // do something on error
      if (canRecover(rejection)) {
        return responseOrNewPromise
      }
      return $q.reject(rejection);
    }
  };
});

$httpProvider.interceptors.push('myHttpInterceptor');


您需要做的就是实现'request'方法,因为所有方法都是可选的。提供的配置对象是一个有角度的$http配置对象,它包含一个headers属性。您应该能够轻松地将标头添加到此:

config.headers.myHeader = myValue;
return config;


您只需在配置博客中将$httpProvider添加到参数列表中即可:

angular
    .module('frontend', [
        ...
    ])
    .config(function($routeProvider, $httpProvider, $provide){
        $routeProvider
            .when(...)

        // register the interceptor as a service
        $provide.factory('myHttpInterceptor', function() {
          return {
            // optional method
            'request': function(config) {
              config.headers.myHeader = myValue;
              return config;
            },
          };
        });

        $httpProvider.interceptors.push('myHttpInterceptor');
    });

07-24 09:44
查看更多