简体   繁体   中英

Angular 2 Http get - parsing JSON object from response

I am trying to parse a JSON object that my server API returns after making an HTTP get request to it. Here is the call to the Http

getPayoutReport(param1, param2, param3) {

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

}

Here is the receiver method:

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

When I log this.payoutReport, I can see a JS Object object in the console. When I examine it in the console, I can see that this has all the properties of the JSON object I need (basically this is the object I need). Except that it is a JS Object object, not the JSON object format I am looking for.

I tried:

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

But then, res.json().data is undefined, and it returns an empty object.

Help appreciated!

Your code looks fine. The problem is that the console.log cannot display a JSON object ... so just displays "object" in the console. Try instead:

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

This converts the value to a string that will appear in the console as you expect.

Use the following code, one file 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 file 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();
            }
        );

    }


}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM