【问题标题】:How can I set Angular values from a config file?如何从配置文件中设置 Angular 值?
【发布时间】:2016-05-09 13:56:07
【问题描述】:

我有一个我必须支持的继承了我的应用程序。到目前为止,它只在一台服务器上运行,我们希望在不同的服务器上运行它。我们在 python 服务器代码和 C++ 客户端代码中到处都发现了对服务器名称的硬编码引用。更改这些以从配置文件中读取服务器名称很容易。但是现在我发现是一个js模块这段代码:

angular.module('app.config', []).constant('config', {"api":"http://foo.bar.com:8001/"});

如何更改此设置,以便从配置文件或其他不需要硬编码的方式动态读取服务器的值?

这是我尝试过的更新:

原来,我的代码是这样的:

angular.module('app.config', []).constant(
  'config', {"api":"http://foo.bar.com:8001/"}
);

我把它改成了这样:

angular.module('app.config').controller('myCtrl', 
  function($scope, $http) { 
    $http.get('./config.json') 
      .then(function(response) { 
        $scope.api = response.data; 
    }); 
});

我得到了这个:

error Module 'app.config' is not available!

然后我改成:

angular.module('app.config', [] ).controller('myCtrl', 
  function($scope, $http) { 
    $http.get('./config.json') 
      .then(function(response) { 
        $scope.api = response.data; 
      }); 
});

然后我得到:

Error: [$injector:unpr] Unknown provider: configProvider <- config <- workitem

我觉得我很接近,我只是需要更多的帮助。

另一个更新:

我试过了:

angular.module('app').controller('home', ['$scope', homeCtrl]);
angular.module('app').controller('workitem', ['$scope', '$routeParams', '$sce', '$timeout', '$http', 'config', workitemCtrl]);
},{"./home/home.js":3,"./workitem/workitem.js":4,"angular":10,"angular-route":6,"angular-sanitize":8,"bootstrap-treeview/src/js/bootstrap-treeview.js":11}],2:[function(require,module,exports){
  module.exports = function($scope,$http) {
      $http.get('config.json').success(function(reponse) {
          console.log("reponse --> "+reponse.api);
          $scope.api = reponse.api;
      });
  }

但当然 app.config 没有得到定义。我怎么能这样做仍然定义 app.config?

我刚试过这个:

var my_config = {};

$.getJSON("config.json", function(data) {
  $.each(data, function(key, val) {
    my_config[key] = val;
  });
});

但是当我在控制器中使用它时,我得到 my_config 没有定义。如何使该变量在控制器中可用?

【问题讨论】:

  • 你的意思是一个单独的.json文件吗?
  • 你在使用 grunt 或 gulp 之类的构建工具吗??
  • 与什么分开?我用于我们的 python 和 C++ 代码的配置文件是简单的键值对。我也想为此使用相同的文件。
  • 如果您使用像 grunt 这样的构建器,您可以轻松地传递一个 Json 配置文件,并让构建工具将 JS 中的占位符字符串替换为上述 conf 文件中的值
  • 不,我们没有使用任何构建工具。这对我们来说可能有点过头了——现在我们只想部署在 2 台主机上。也许还有几个,但都在家里。我只是不想为每个主机使用不同的 js 文件。

标签: javascript angularjs


【解决方案1】:

试试这个

angular.module('app.config', [])
.constant('bbConfig',{ 
     "api":"http://foo.bar.com:8001/"
 });

在控制器中

angular.module('app.config', [])
.controller('MainCtrl',['$scope', 'bbConfig' , function ($scope, bbConfig){
    console.log(bbConfig.api)
}]);

【讨论】:

  • 我喜欢这个解决方案,因为这个文件现在变成了一个普通的配置文件。换句话说,它不再存在于版本中,而是在它部署的每个实例中进行管理。
  • 我会将代码放在第一个块的什么位置?在一个文件中?该文件在哪里引用?
【解决方案2】:

创建一个服务来读取配置(json 文件)或调用服务器并将响应 URL 存储在 LocalStorage 中,如下所示。您可以从任何地方访问它

$localStorage.api = response.Url ; //http://foo.bar.com:8001/

【讨论】:

    【解决方案3】:

    我终于能够通过预先完成这项工作来完成这项工作:

    angular.module('app').value('config', {
      api: ''
    });
    
    angular.module('app').run(function($rootScope, $http, config) {
      $http.get('config/config.json').then(function(response) {
            config.api = response.data.api;
            $rootScope.$broadcast('config-loaded');
        });
    });
    

    将主要代码包装在:

    var init = function(){
    }
    

    并在最后添加:

    if (config.api) {
      init()
    } else {
        var configLoaded = scope.$on('config-loaded', function() {
            init();
            configLoaded();
        });
    }
    

    【讨论】:

      【解决方案4】:

      你可以这样做:

      1. 使用 ngConstant 构建任务将您的独立配置文件以 JSON 格式包装到包含的 angular.config 数据中。 假设你有app/config.json 文件:

        { “myFirstCnt”:是的, “mySecondCnt”:{“你好”:“世界”} }

      然后在构建中运行 ngConstant 任务后,您将获得 dist/config.js(输出)将是:

      define(["require", "exports"], function(require, exports) {
        return angular.module("my.module.config", ["ngAnimate"])
          .constant("myFirstCnt", true)
          .constant("mySecondCnt", { "hello": "world" })
          .constant("myPropCnt", "hola!");
      });
      

      Gulp pluginGrunt pluginmore on ngConstant

      1. 在服务或控制器中应用引导后立即使用服务加载 JSON 文件:

      应该避免这种情况:

      app.controller('myCtrl', 
        function($scope, $http) {
          $http.get('PATH_TO/config.json').then(function(response) {
            $scope.myWelcome = response.data;
          });
        }
      );
      

      更多关于这种方式的例子在这里:Reading in JSON through Angular Resources Service

      UPD 12-06

      要解析加载的 JSON,试试这个:

      for (var name in data) {
        if (data.hasOwnProperty(var)) {
           my_config[var] = data[var];
        }
      }
      

      【讨论】:

      • More info 在这个方法上。
      • @Ankh,那个是关于 AngularJS 2.x 版本的,而这里是 1.x
      • 当我使用app.controller 时出现错误。我将其更改为:angular.module('app').controller('myCtrl', function($scope, $http) { $http.get('./config.json') .then(function(response) { $scope.api = response.data; }); });,现在稍后在脚本中引用 app.config 时出现错误 Module 'app.config' is not available!
      • 您应该在该代码行中将数据传递给 $scope.api:$scope.api = response.data;或者将命名改为$rootScope.api,那么它将在所有控制器中可用
      • 猜我不明白我需要做什么。我将所有对$scope.config.api 的引用更改为$scope.api,但我得到了同样的错误。还尝试将分配更改为$rootScope.api = response.data 并得到相同的错误。
      猜你喜欢
      • 1970-01-01
      • 2011-03-08
      • 1970-01-01
      • 2012-09-10
      • 2019-09-20
      • 2020-10-31
      • 2015-05-04
      • 2017-02-15
      • 2020-08-07
      相关资源
      最近更新 更多