【问题标题】:How to inject module and make it accesible to entrie angular app如何注入模块并使其可供整个 Angular 应用程序访问
【发布时间】:2015-05-13 16:13:44
【问题描述】:

我有一个模块 (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”,使其也可以在所有模块(module#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 单独注入每个模块。还有其他解决方案吗?

【问题讨论】:

    标签: angularjs angular-services


    【解决方案1】:

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

    function ServiceOne($http, NAME1) {
    
       var service = {...
       ...
    
     }
    

    这是一个很好的explanation

    【讨论】:

      【解决方案2】:

      你可以设置一个配置对象

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

      【讨论】:

        【解决方案3】:

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2013-07-30
          • 1970-01-01
          • 2017-11-15
          • 1970-01-01
          • 2016-11-29
          • 2014-04-21
          • 1970-01-01
          • 2020-12-14
          相关资源
          最近更新 更多