Search code examples
angularjsangularjs-bootstrap

Access constants from super module within included modules (config())


I have a global module 'app' which include two other modules 'app.core' and 'app.service'. This is basic settings. Inside the two sub module I can access the constant from both two modules. However I cannot access constants declared in 'app' within 'app.core' or 'app.service'.

Also I use angular.bootstrap to delay my initialization because I need to retrieve a config from server. But after receiving the config I do angular.module('app').constant('config', config); So the constant should be well defined..

LAst point, inside the 'app' module config I can access the config constant.

Any idea ?

'app' module constants declaration

angular.module('app',[
    'app.core',
    'app.service'
])
    .module('app')
    .constant('foo', 'foo')

'app.core' constants

    angular
    .module('app.core')
    .constant('core', 'core');

In 'app.service' I can get core constant

    angular.module('app.services',[]).config(function($injector){
        console.log($injector.get('core'));
    })

But I cannot retrieve 'app' constant

angular.module('app.services',[]).config(function($injector){
        console.log($injector.get('foo'));
    })

Will crash


Solution

  • In both configurations you are trying to access a constant defined within a separate module, but then not defining that module as a dependency. How, for example, can app.services have access to foo when foo is defined on a module which requires app.services in the first place?

    The reason that core is available to app.services despite this is because you have listed the dependencies in such an order when defining app that angular happens to have loaded app.core prior to app.services. The order of the defined dependencies, however, should not matter.

    In order to correct this, you should consider refactoring your modules so that there is no inherent circular dependency. For example, consider making your config a module in itself and inject it into the dependent services:

    angular.module('app', ['app.core', 'app.services'])
    
    angular.module('app.config', [])
      .constant('foo', 'foo')
    
    angular.module('app.core', ['app.config'])
      .config(function(foo) {})
    
    angular.module('app.services', ['app.config'])
      .config(function(foo) {})
    

    Note also that using the injector to get constants is un-necessary as they can be injected directly during the configuration stage.