在父模块上运行的块会在子模块中的代码之前运行吗?

Will a block run on a parent module run before code in the child module?

本文关键字:运行 模块 代码      更新时间:2023-09-26

考虑这样一个angular应用程序(在我的手机上写的,抱歉语法奇怪):

angular.module('app1').controller(ctrl1, function($http){
    $http.get(...);
});
angular.module('app2', ['app1']).run(function($http){
    $http.default.headers.common.foo = 'bar';
});

运行块是否保证在控制器代码之前运行?换句话说,如果我通过调用app2来加载页面,我能保证所有HTTP调用都有默认的标头吗?

确实,'run'块将在运行阶段被调用,这是在控制器初始化之前。

但是,我建议您在配置阶段通过$httpProvider.interceptors配置默认头:

app.factory('httpRequestInterceptor', function () {
    return {
        request: function (config) {
            config.headers['foo'] = 'bar';
            return config;
        }
    };
});
app.config(function ($httpProvider) {
    $httpProvider.interceptors.push('httpRequestInterceptor');
});