繁体   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