[英]How to read the json config file inside angular module?
I am writing the javascript, AngularJS app using typescript. 我正在使用typescript编写javascript,AngularJS应用程序。 Also I am using grunt for building.
我也在使用grunt进行建设。 In fact I have started off with ng boilerplate .
事实上,我已经开始使用ng样板了 。
Now suppose I have a config.json
file something like below- 现在假设我有一个类似于下面的
config.json
文件 -
{
"app": "abc",
"login": "xyz"
}
I want some variables in my app to be configurable. 我希望我的应用程序中的一些变量是可配置的。 So at some place I could use something like -
所以在某些地方我可以使用像 -
var loginUrl : string = "def?pqr="+config.app;
Now how can I read this config in my javascript files? 现在我如何在我的javascript文件中读取此配置? I am looking for best practice answer.
我正在寻找最佳实践答案。 I am fine with substitution at
grunt build
step also. 我也可以在
grunt build
步骤中替换。
Note: The config file is present on client itself, ie no need to load it from server separately. 注意:配置文件存在于客户端本身,即无需单独从服务器加载。
In my case, I use grunt to inject a config file (shared with the server) in an angular constant module : 在我的例子中,我使用grunt在角度常量模块中注入一个配置文件(与服务器共享):
Using grunt-preprocess : 使用grunt-preprocess :
I having a config.tpl.js with : 我有一个config.tpl.js:
angular.module('app.config', [])
.constant('appConfig', {
// clientside specific constants
var1 : 'value1',
var2 : [1,2,3],
sharedVars : /* @echo SHARED_VARS */
});
Then, in my gruntFile : 然后,在我的gruntFile中:
preprocess: {
options: {
context: {
SHARED_VARS: grunt.file.read('config.json'),
}
},
config: {
src: 'src/config.tpl.js',
dest: 'src/config.js' // true file generated and loaded in index.html
}
},
That way you can inject a full config file in an angular constant module, or pick only the vars you want. 这样,您可以在角度常量模块中注入完整的配置文件,或者只选择您想要的变量。
For client side code you should just use $http.get
to get the json file from the server. 对于客户端代码,您应该使用
$http.get
从服务器获取json文件。 Assuming the json file is http accessible at /manage/config.json
you would do: 假设json文件在
/manage/config.json
可以访问http,你可以这样做:
$http.get('/manage/config.json').then((res)=>{
var config = res.data;
});
$http automatically does json parsing for you. $ http会自动为您解析json。
here is what i did 这就是我所做的
var initInjector = angular.injector(['ng']);
var $http = initInjector.get('$http');
var configModule = angular.module('portalConfig', []);
$http.get('../config/Settings.json').then(
function (response) {
configModule.value('config', response.data);
}
);
and then suppose your app module is foo then 然后假设你的app模块是foo
angular.module('foo',['portalConfig'])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.