如何读取角度2中的配置文件条目?

Kri*_*nan 8 angular

我需要读取json格式的配置文件.json文件包含键/对值中的配置条目.如何获取任何特定键的值?

我的问题是,我可以使用http.get()或任何其他方式读取整个json文件,但是如何根据键获取特定的配置值?我应该循环/迭代项目以获得所需的项目还是有其他更好的方法来做到这一点?

我的json配置如下所示

{
  "SecurityService": "http://localhost/SecurityAPI",
  "CacheService": "http://localhost/CacheServiceAPI"
}
Run Code Online (Sandbox Code Playgroud)

我按照你的建议尝试进行代码更改从json文件中读取配置数据的代码

getConfiguration = (): Observable<Response> => {
        return this.http.get('config.json').map(res => res.json());
    }
Run Code Online (Sandbox Code Playgroud)

以下代码从调用组件调用上述方法并使用read配置值

this._ConfigurationService.getConfiguration()
            .subscribe(
            (res) => {
                this.configs = res;
                console.log(this.configs);
            },
            (error) => console.log("error : " + error),
            () => console.log('Error in GetApplication in Login : ' + Error)
        );
Run Code Online (Sandbox Code Playgroud)

但是当上面的内容被执行时,我得到的错误是

"error : SyntaxError: Unexpected token < in JSON at position 0"

我在这里做的错误是什么,读取json文件的相同代码在我需要从json读取数据并绑定网格等的其他场景中有效.

我试过在plunkr中重现这个问题https://plnkr.co/edit/rq9uIxcFJUlxSebO2Ihz?p=preview

eko*_*eko 15

"读取"配置文件与读取js中的任何其他对象没有什么不同.例如,创建一个配置变量:

export var config = {
  title: "Hello World",
  "SecurityService":"http://localhost/SecurityAPI",
  "CacheService":"http://localhost/CacheServiceAPI"
}
Run Code Online (Sandbox Code Playgroud)

然后将其导入您的组件以使用它:

import { Component, Input } from '@angular/core';
import { config } from './config';

@Component({
  selector: 'my-app',
  template: `{{myTitle}}<br>{{security}}<br> {{cache}}`,
  directives: []
})
export class AppComponent {
    myTitle = config.title;
    security = config.SecurityService;
    cache = config.CacheService;

}
Run Code Online (Sandbox Code Playgroud)

完整示例:https://plnkr.co/edit/CGtxYJkcjYt2cEzrbL00?p = preview

  • 我不想在.ts文件中有配置条目.相反,它应该来自一个json文件. (2认同)