您应该为此使用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');
});
启动(https://docs.angularjs.org/api/ng/provider/$httpProvider) – charlietfl