簡體   English   中英

Angular 2 Http get - 從響應中解析JSON對象

[英]Angular 2 Http get - parsing JSON object from response

我正在嘗試解析我的服務器API在向它發出HTTP get請求后返回的JSON對象。 這是對Http的調用

getPayoutReport(param1, param2, param3) {

    //do some hanky panky
    //configure a requestUrl
    return this.http.get(this.requestUrl).map((res:Response)=> res.json());

}

這是接收方法:

this.payoutReportsService.getPayoutReport(this.reservationId, this.productId, this.vendor)
        .subscribe(data => {this.payoutReport = data; console.log(this.payoutReport);});

當我記錄this.payoutReport時,我可以在控制台中看到一個JS Object對象。 當我在控制台中檢查它時,我可以看到它具有我需要的JSON對象的所有屬性(基本上這是我需要的對象)。 除了它是一個JS Object對象,而不是我正在尋找的JSON對象格式。

我試過了:

 return this.http.get(this.requestUrl).map(this.extractData);
 private extractData(res: Response) {
    let body = res.json();
    return body.data || { };
}

但是,res.json()。數據是未定義的,它返回一個空對象。

幫助贊賞!

你的代碼看起來很好。 問題是console.log無法顯示JSON對象...所以只需在控制台中顯示“對象”。 嘗試改為:

console.log(JSON.stringify(this.payoutReport));

這會將值轉換為將按預期顯示在控制台中的字符串。

使用以下代碼,一個文件json.service.ts

import { Injectable } from '@angular/core';
import { Http, RequestOptions, Headers } from '@angular/http';

@Injectable()
export class JsonService {
    private _baseUrl = 'http://server/jsonfile';

    constructor( private _http: Http ) {
    }

    getJson() {

        return  this._http.get(this._baseUrl');        
    }

}

組件文件component.component.ts

import { JsonService } from './json.service';
import { Component, OnInit } from '@angular/core';

@Component({
    ...
})

export class ComponentObject implements OnInit {

    private jsonObject;

    constructor (private _JsonService: JsonService){

    }

    ngOnInit(){        
        this.getJson();
        //at this moment you can use the internal Json 
        //properties or json arrays of the Json object sample:
        //this.JsonObject.jsonPropertie


    }

    private async getJson() {

        let value;
        let promise;
        promise = await  this._JsonService.getJson().toPromise().then(
            res => {
                this.JsonObject = res.json();
            }
        );

    }


}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM