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

时间:2017-11-18 13:24:38

标签: javascript angularjs

我刚刚使用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,但我该怎么办呢?

2 个答案:

答案 0 :(得分:1)

您应该使用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');
    });

答案 1 :(得分:1)

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

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