我正在创建一个与 Node 后端快速应用程序对话的 Angular 应用程序,并使用配置文件在我的 Node 应用程序中设置环境变量我可以像这样访问我的配置文件:
index.js
var port = config.get("server:port");
var server = app.listen(port, function() {});
我的配置文件是这样的:
app.config.js
module.exports =
{
"server":{
"host":"localhost",
"port":3000
},
"mongodb": "",
"redis": {
"loadBalancerInstance": {
"host": "server",
"port": {
"default": "6379"
}
}
},
"elastic": {
"server": "server",
"port": "9200",
"user":"foo",
"password":"bar"
},
"log": {
"level": "info",
"filename": "",
"console": true,
"logio": {
"port": "28777",
"node_name": "this-server-name",
"host": "server"
}
}
};
我已经静态定义了到后端的路由/端口
datafactory.js
angular.module('dashboard.factories')
.factory('DataFactory', function($http, $q, FormatFactory) {
var backend = function(apiEndPoint, clientKey) {
clientKey = clientKey || "";
var deferred = $q.defer();
$http.get("http://localhost:3000/<-(pull this from config file)" + apiEndPoint + "/" + clientKey)
我的问题是如何在 Angular 服务中访问 app.config.js 并在我的 Angular 服务中动态设置主机/端口
最佳答案
我想如果您坚持使用 Node 服务器使用的相同配置文件,则必须使 .js 文件可用于您应用的 GET 请求,然后您必须解析该文件将字符串转换为 JSON。
编辑: 您将必须有两个配置文件,一个可用于您的 Node 服务器,一个可用于您的 Angular 应用程序。现在,如果您希望源是一个文件,您可以将其构建到您的构建过程中——如果您使用 gulp 或 grunt 之类的东西,这将相当容易。它可以采用单个配置文件并构建两个文件 - Node 服务器配置文件和一个可以注入(inject)数据服务的 Angular 模块(我建议使用常量或值)。
关于javascript - 将配置文件与angularjs一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32574769/