如何读取角度模块内的json配置文件?

Vin*_*arg 10 javascript json angularjs gruntjs typescript

我正在使用typescript编写javascript,AngularJS应用程序.我也在使用grunt进行建设.事实上,我已经开始使用ng样板了.

现在假设我有一个config.json类似下面的文件 -

{
    "app": "abc",
    "login": "xyz" 
}
Run Code Online (Sandbox Code Playgroud)

我希望我的应用程序中的一些变量是可配置的.所以在某些地方我可以使用类似的东西 -

var loginUrl : string = "def?pqr="+config.app;
Run Code Online (Sandbox Code Playgroud)

现在我如何在我的javascript文件中读取此配置?我正在寻找最佳实践答案.我grunt build也可以在步骤中替换.

注意:配置文件存在于客户端本身,即无需单独从服务器加载.

Cét*_*tia 7

在我的例子中,我使用grunt在角度常量模块中注入一个配置文件(与服务器共享):

使用grunt-preprocess:

我有一个config.tpl.js:

angular.module('app.config', [])

.constant('appConfig', {

    // clientside specific constants
    var1                        : 'value1',
    var2                        : [1,2,3],
    sharedVars                  : /* @echo SHARED_VARS */
});
Run Code Online (Sandbox Code Playgroud)

然后,在我的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
    }
},
Run Code Online (Sandbox Code Playgroud)

这样,您可以在角度常量模块中注入完整的配置文件,或者只选择您想要的变量.


bas*_*rat 5

对于客户端代码,您应该只使用$http.get从服务器获取json文件.假设json文件是http可访问的,/manage/config.json你会这样做:

$http.get('/manage/config.json').then((res)=>{
     var config = res.data;
});
Run Code Online (Sandbox Code Playgroud)

$ http会自动为您解析json.