如何注入模块并使其可供应用程序的所有模块和子模块访问(获取未知提供程序错误)

How to inject a module and make it accesible to all modules and submodules of app (getting unknown provider error)

请注意这是不是的副本:

我有一个模块 (app.config),我想将其注入到我的整个应用程序中。

该模块需要在注入到 myApp

的所有其他模块和子模块(模块内的模块)中可访问

例如,我的应用程序如下所示:

angular.module('myApp', [
    'app.config',
    'module#1',
    'module#2',
    'module#3',
    'module#4'    
])
.config...

///////////////////////////////

这里是app.config

angular.module('app.config', []).
    constant('NAME1', 'Name1').
    constant('NAME2', 'Name2'); 
////////////////////

我希望 'app.config' 以这样的方式注入,它应该可以在 module#500 中访问,这不是 'myApp' 的直接依赖,而是 module#1 的依赖- 反过来,它是 myApp.

的依赖项

module#1 是这样定义的(如图所示,module#500module#1 的依赖项):

 angular.module('module#1', [
        'module#500',
        'module#501',
        'module#502',
        ...    
    ]);

这是我的问题:

angular.module('module#500', []).
    service('serviceOne', serviceOne);

function ServiceOne($http, NAME1) {

    var service = {
        getMyProfile: function(){return $http.get('api/' + NAME1);}
    };

    return service;
}

问题 - 我得到一个错误-> Uncaught Error: [$injector:unpr] Unknown provider: NAME1Provider <-NAME1 <- serviceOne 但我以为我把它注入了整个应用程序???

我不想将 module#500 作为依赖项直接添加到 'myApp' 我不想将 module#500 作为依赖项module#1。我想将 module#1 作为 myApp

的依赖

我也不想单独注入 app.config 到每个模块。 还有其他解决方案吗?

您忘记在 ServiceOne 服务中注入 NAME1

例如:function ServiceOne($http, NAME1)

I don't want to individually inject app.config to each and every module either. Any other solutions?

我不知道您希望得到什么解决方案?有了这一行:angular.module('module#500', []). module#500 怎么会知道其他任何事情,它什么也没给它。也许我在这里误解了什么。

编辑,因为我刚刚阅读了您的 post 和昨天的评论:我认为您没有正确理解依赖注入。它只有一种方式,模块#1 可以访问模块#500,但是模块#500 不能访问模块#1。它必须是这样的:如果模块#500 有一些依赖于模块#1 的行为,而在其代码中的任何地方都没有提到,你怎么能对模块#500 进行单元测试?

猜测如果您的项目都依赖于相同的配置变量,那么您的项目实际上并不需要那么多模块。那些依赖于配置变量的工厂和服务应该与它在同一个模块中。这是适当的划分,从长远来看会让你的生活更轻松 运行。

如果你不想让 myApp 依赖于 app.config(尽管这样做是正确的,因为它的子模块 depend),你可以通过手动引导加载配置模块

angular.bootstrap(document, ['myApp', 'app.config']);

而不是 ng-app="myApp"