我需要读取json格式的配置文件。 json文件包含键/值对中的配置条目。我如何获得任何特定密钥的值?如何读取角度2中的配置文件条目?
我的问题是,我可以阅读整个使用http.get()或任何其他方式的json文件,但我如何得到一个特定的配置值基于一个关键?我是否需要循环/迭代项目才能获得所需的项目,还是有其他更好的方法来完成它?
的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数据并结合电网等
我曾尝试在plunkr https://plnkr.co/edit/rq9uIxcFJUlxSebO2Ihz?p=preview
你可以做'数据[“SecurityService “]'或'data.SecurityService' –
你检查过JSON吗?如果你得到这个错误,这可能是一个HTML回应。这就是说数据的第一个标记是'<',这是无效的JSON。当你尝试调用'res.json()'时,会发生这种情况,调用JSON.parse –
添加'http.get(..)。do(res => console.log(res.text()))'你得到。如果它是HTML,那么找出原因。 –