2017-05-16 7 views
3
私はファイル location.jsonを持って

内のオブジェクトへオブジェクトにjson文字列を解析しますか?活字体、角度2解析JSONの形式のJSON文字列を含む、HTTP

... 
export class DashboardComponent { 

    locations: Locations[]; 

    constructor(private locationService:LocationService) { 
    this.getLocations() 
    } 

    getLocations(){ 
     this.locationService.get('assets/location.json') 
     .subscribe(res => this.location = res); 
    } 
+0

を –

+0

これは私のJSONをマップしませんでした。 – Kenadet

答えて

0

通常、それ以外の場合は解析できないだろう、あなたはserviceメソッドでres => res.json()どこかで応答をマッピングするが、JSONは有効なフォーマットを持っている必要があります。私はこのような何かをしました。

レスポンスはObjectであり、レスポンスの本体だけを解析することはできません。

return this.http.get(url,options).map((response) => this.parseResponse(response)) 
     .catch((err) => this.handleError(err)); 

    private handleError(error: any) { 
    let body = error.json(); 

    return Observable.throw(body); 
    } 

    private parseResponse(response: Response) { 
    return response.json(); 
    } 
+0

例を挙げることができますか? – Kenadet

+0

ありがとう、しかし、私はまだマッピングを見た...私はNgForの '場所'にできるはずです。 – Kenadet

+0

json以外のものが発行された場合は、構造が異なるため、結果をより良く変換できます。 –

5

subsriberための結果だ内容に応じてそれができる:

.map(res => this.location = res.json().locations); 

または:

.subscribe(res => this.location = JSON.parse(res).locations); 

しかし、それはあなたのクラスのインスタンスをinstiantiateないであろうことに注意してください、次の値に一致する正規のjsオブジェクトとしてのみ値を割り当てます。

interface Location { 
    id: number; 
    places: Place[]; 
} 

interface Place { 
    id: number; 
    city: string; 
    state: string; 
} 

あなたが何か行う必要がありますクラスのインスタンスたい場合は210:多分JSON.Parse(RES)にしてみてください

JSON.parse(res) 
    .locations.map(location => new Location(location.id, 
     location.places.map(place => new Place(place.id, place.city, place.state))) 
+0

私は' JSON.parse'を実行したときに '例外:予期しないトークンoをJSONの1の位に置いています ' – Kenadet

+0

もう一度、それはあなたのものに依存しています。これを追加してください: 'console.log(res、typeof res)'実際のレスポンスは何ですか? –

関連する問題