【发布时间】: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