如何注入模块并使其可供整个 angular 应用程序访问

How to inject module and make it accesible to entrie angular app

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

该模块需要在注入应用程序的所有其他模块中都可以访问

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

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' 以可以在所有模块(模块#1'、'module#2'、...)中访问的方式注入。

这是我的问题:

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

function ServiceOne($http) {

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

    return service;
}

问题 -> NAME1 未定义。 但我以为我将它注入了整个应用程序???

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

您还需要将常量注入控制器。

function ServiceOne($http, NAME1) {

   var service = {...
   ...

 }

这里不错explanation

NAME1 是 Angular 知道注入常量的关键,但您从未注入过它!此外,您需要添加对在 'Module1' 中设置常量(在本例中为 'app.config')的模块的依赖。另外,当我创建服务时,我只是将方法添加到 this 中,这是对服务本身的引用,所以我不需要费心为服务创建对象并像你一样返回它在你的例子中做。最后,最好使用 inline array annotation for dependency injection,如下面的示例所示。试试这个:

var mod1 = angular.module('Module1', ['app.config']);

mod1.service('ServiceOne', ['$http', 'NAME1', serviceOne]);

function ServiceOne($http, NAME1) {

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

}

您可以设置一个配置对象

app.config

module.exports = {
    NAME1: 'Name1',
    NAME2: 'Name2'
}

然后

var config = require('../config');

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

function ServiceOne($http) {

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

    return service;
}