我需要讀取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,那麼找出原因。 –