Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angularjs/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 在父模块上运行的块是否会先于子模块中的代码运行?_Javascript_Angularjs_Http - Fatal编程技术网

Javascript 在父模块上运行的块是否会先于子模块中的代码运行?

Javascript 在父模块上运行的块是否会先于子模块中的代码运行?,javascript,angularjs,http,Javascript,Angularjs,Http,考虑这样一个有角度的应用程序(写在我的手机上,抱歉语法怪异): 运行块是否保证在控制器代码之前运行?换句话说,如果我通过调用app2加载我的页面,我是否可以保证所有HTTP调用都有默认的头?实际上,“运行”块将在控制器初始化之前的运行阶段被调用 但是,我建议您在配置阶段通过$httpProvider.interceptors配置默认头: app.factory('httpRequestInterceptor', function () { return { request

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


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

实际上,“运行”块将在控制器初始化之前的运行阶段被调用

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

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

app.config(function ($httpProvider) {
    $httpProvider.interceptors.push('httpRequestInterceptor');
});

为什么拦截器会更好?似乎有更多的代码可以做到这一点thing@DavidGrinberg由于配置阶段是为配置而设计的(这正是我们实际要做的),而run在对象实例注册后执行任何类型的初始化都可能很有用,因此最好使用config。此外,在运行阶段,您可以使用服务,这意味着在配置默认标头之前有机会发送请求。如果在
.config()
app.factory('httpRequestInterceptor', function () {
    return {
        request: function (config) {
            config.headers['foo'] = 'bar';
            return config;
        }
    };
});

app.config(function ($httpProvider) {
    $httpProvider.interceptors.push('httpRequestInterceptor');
});