2016-12-06 30 views
6

我需要讀取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

+0

你可以做'數據[「SecurityService 「]'或'data.SecurityService' –

+0

你檢查過JSON嗎?如果你得到這個錯誤,這可能是一個HTML迴應。這就是說數據的第一個標記是'<',這是無效的JSON。當你嘗試調用'res.json()'時,會發生這種情況,調用JSON.parse –

+0

添加'http.get(..)。do(res => console.log(res.text()))'你得到。如果它是HTML,那麼找出原因。 –

回答

10

重現問題「閱讀」配置文件是不是在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

+1

我不想在.ts文件中的配置項。相反,它應該來自json文件。 – Krishnan

+0

@Krishnan我剛剛創建了一個例子json。你看'var config'是一個json(javascript對象)。無論你在哪裏獲得這個json數據,你都可以簡單地使用點(config.SecurityService')或數組表示法('config [「SecurityService」]')來選擇它的關鍵字@Pankaj也在評論 – echonax

+0

中提到錯誤爲「error:SyntaxError:意外的標記 Krishnan