【问题标题】:Angularjs - Dynamic configuration based on EnvironmentAngularjs - 基于环境的动态配置
【发布时间】:2016-05-24 00:48:18
【问题描述】:

我有一个示例 Angular APP - app.js

angular
    .module('myUiApp', [
        'restangular',
        'ngRoute',
        'ngCookies',
        'ui.bootstrap',
        'ui.sortable',
        'smart-table',
        'config'
    ])
    .config(function($routeProvider, $httpProvider, $sceProvider, $logProvider, RestangularProvider, config) {
        RestangularProvider.setBaseUrl(config.apiBaseUrl);
        RestangularProvider.setDefaultHeaders({'Content-Type': 'application/json'});
//routing here
.....
});

我的 Config.js 看起来像 -

angular.module('config', []).service('config', function($location, ENV) {
    return ENV.dev;
});

我的 constants.js 看起来像 -

'use strict';

 angular.module('config', []).constant('ENV', (function() {
    return {
    dev: {
    appBaseUrl:'http://localhost:9000/',
    apiBaseUrl:'http://localhost:8082/api/'
    }
}
})());

我收到错误消息,无法实例化模块 myUiApp,原因是: [$injector:unpr] 未知提供者:配置。

我的假设是注入配置模块将调用服务,然后返回 json 对象。有什么想法或建议可以更好地进行此动态配置?

【问题讨论】:

    标签: javascript angularjs


    【解决方案1】:

    您只能将providers 注入到有角度的.config() 块中。您正在尝试注入 service,这可能是您的错误的原因。

    另外,angular.module('config', []) 在两个不同的地方。这应该只使用一次来实例化模块。随后使用angular.module('config')(不带第二个参数)来引用该模块。

    【讨论】:

      【解决方案2】:

      我会避免调用模块 config,而是使用不是 angular module.config() 使用的方法的东西——也许是 myConfigModule

      其次,确保您的脚本在包含 app.js 文件之前包含 constants.js 文件和 Config.js 文件

      最后仔细检查一下这种情况不会影响你:

      用angular.module('config', []) 定义模块两次(强调[ ] ..)当你用方括号定义模块时,你说的是“新模块”。在您包含的第二个文件中,将其更改为 angular.module('config') - 或者,将这些文件合并为:

      angular.module('myConfigModule', [])
      .constant('ENV', (function() {
      return {
          dev: {
              appBaseUrl:'http://localhost:9000/',
              apiBaseUrl:'http://localhost:8082/api/'
              }
          }
      }).service('config', function($location, ENV) {
          return ENV.dev;
      });
      

      更新:通常我会看到这种语法用于控制器、服务以及注入其他任何东西的任何东西

      .service('config', ['$location', 'ENV', function($location, ENV) {
           return ENV.dev;
      }]); // see beginning and end of square bracket
      //  also add new injected modules to both the array (surrounded by quotes) and the function
      

      【讨论】:

      • 谢谢!。在我的 app.js 中,我使用了 myConfigModule 和配置服务。仍然收到“未知提供者:配置”。
      • 我搞定了。感谢您的两位cmets。一个快速的问题.. 如何在 app.js config() 块中注入服务?
      • 使用更新答案中的语法注入服务
      猜你喜欢
      • 2011-08-15
      • 2018-07-10
      • 2020-12-27
      • 1970-01-01
      • 2019-05-22
      • 2021-12-25
      • 2015-10-20
      • 2014-09-01
      • 1970-01-01
      相关资源
      最近更新 更多