David Grinberg David Grinberg - 5 months ago 21
AngularJS Question

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

Consider an angular app like so (written on my phone, sorry for weird syntax):

angular.module('app1').controller(ctrl1, function($http){
$http.get(...);
});

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


Is the run block guaranteed to run before the controller code? In other words, if I load my page by calling app2, will I be guaranteed that all HTTP calls will have the default header?

Answer

Indeed, 'run' block will be invoked during run phase, which is before controller's initialization.

However, I'd recommend you to configure default headers on config phase via $httpProvider.interceptors:

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

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