将标头添加到Yeoman创建的AngularJS应用程序中的所有请求



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

$ 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');
    });

在所有请求中添加标头的更好解决方案是

app.run(['$http', function ($http) {
   $http.defaults.headers.common['myHeader'] = 'myHeaderValue';
}]);

相关内容

最新更新