【问题标题】:Angular 2 Http get - parsing JSON object from responseAngular 2 Http get - 从响应中解析 JSON 对象
【发布时间】:2017-12-04 21:35:42
【问题描述】:

我正在尝试解析我的服务器 API 在向它发出 HTTP 获取请求后返回的 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().data 是未定义的,它返回一个空对象。

帮助表示赞赏!

【问题讨论】:

  • 当你放res.json()时,它把json对象转换成js对象,有什么问题
  • 不知道为什么这被否决了。除了关于 JSON 对象的术语混乱之外,这似乎是一个有效的问题。

标签: javascript json angular observable


【解决方案1】:

您的代码看起来不错。问题是console.log 无法显示JSON 对象......所以只在控制台中显示“对象”。试试吧:

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

这会将值转换为一个字符串,该字符串将按您的预期显示在控制台中。

【讨论】:

  • 感谢您的帮助!
【解决方案2】:

使用如下代码,一个文件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();
            }
        );

    }


}

【讨论】:

  • 有趣的是,我在第一个 Angular 2/4 示例中看到了这个“.json()”。只是,当我需要它时,我忘记了确切的语法,而且我在任何地方都找不到它。谢谢。
猜你喜欢
  • 1970-01-01
  • 2017-10-15
  • 1970-01-01
  • 2011-08-09
  • 1970-01-01
  • 2020-12-24
  • 1970-01-01
  • 2021-12-09
  • 1970-01-01
相关资源
最近更新 更多