1

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

4

1 回答 1

3

在这两种配置中,您都试图访问在单独模块中定义的常量,但随后不将该模块定义为依赖项。例如,如何app.services访问foo何时在首先需要foo的模块上定义? app.services

core尽管如此,仍然可以使用的原因app.services是因为您在定义appangular 恰好app.coreapp.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) {})

另请注意,使用注入器获取常量是不必要的,因为它们可以在配置阶段直接注入。

于 2015-02-02T21:11:53.783 回答