我需要读取json格式的配置文件。 json文件包含键/对值中的配置条目。如何获取任何特定键的值?
我的问题是,我可以使用http.get()或其他任何方式从整体上读取json文件,但是如何基于 key 获取特定的配置值?我是否需要循环遍历/迭代这些项目以获得所需的项目,或者还有其他更好的方法吗?
我的json配置如下所示
{
"SecurityService": "http://localhost/SecurityAPI",
"CacheService": "http://localhost/CacheServiceAPI"
}
我尝试根据您的建议进行代码更改
从json文件读取配置数据的代码
getConfiguration = (): Observable<Response> => {
return this.http.get('config.json').map(res => res.json());
}
以下代码从调用组件调用上述方法并使用读取的配置值
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)
);
但是当上面的代码被执行时,我得到的错误是
"error : SyntaxError: Unexpected token < in JSON at position 0"
我在这里犯的错误是什么,读取json文件的相同代码在其他需要从json读取数据并绑定(bind)网格等情况下也适用。
我尝试在plunkr https://plnkr.co/edit/rq9uIxcFJUlxSebO2Ihz?p=preview中重现该问题
最佳答案
“读取”配置文件与读取js中的任何其他对象没有什么不同。例如,创建一个配置变量:
export var config = {
title: "Hello World",
"SecurityService":"http://localhost/SecurityAPI",
"CacheService":"http://localhost/CacheServiceAPI"
}
然后将其导入到您的组件以使用它,如下所示:
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;
}
完整示例:https://plnkr.co/edit/CGtxYJkcjYt2cEzrbL00?p=preview