考虑像这样的 Angular 应用程序(在我的手机上编写,抱歉语法奇怪):
angular.module('app1').controller(ctrl1, function($http){
$http.get(...);
});
angular.module('app2', ['app1']).run(function($http){
$http.default.headers.common.foo = 'bar';
});
运行 block 是否保证在 Controller 代码之前运行?换句话说,如果我通过调用 app2 加载页面,是否可以保证所有 HTTP 调用都具有默认 header ?
最佳答案
事实上,“运行” block 将在运行阶段调用,即在 Controller 初始化之前。
但是,我建议您通过 $httpProvider.interceptors
在配置阶段配置默认 header :
app.factory('httpRequestInterceptor', function () {
return {
request: function (config) {
config.headers['foo'] = 'bar';
return config;
}
};
});
app.config(function ($httpProvider) {
$httpProvider.interceptors.push('httpRequestInterceptor');
});
关于javascript - 父模块上的 block 会在子模块中的代码之前运行吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38151949/