如何注入模块并使其可以访问entrie角度应用程序

时间:2015-05-13 16:13:44

标签: angularjs angular-services

我有一个模块(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',模块#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。其他任何解决方案?

3 个答案:

答案 0 :(得分:3)

你也需要将常量注入控制器。

function ServiceOne($http, NAME1) {

   var service = {...
   ...

 }

这是一个很好的explanation

答案 1 :(得分:0)

NAME1是Angular知道注入常量的关键,但你从来没有注入它!此外,您需要在'app.config'中的模块中添加依赖项,在该模块中设置常量(在本例中为'Module1')。此外,当我创建服务时,我只是将方法添加到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);
  };

}

答案 2 :(得分:0)

您可以设置配置对象

的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;
}