javascript - Angular 2 Http get - 从响应中解析 JSON 对象

标签 javascript json angular observable

我正在尝试解析我的服务器 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().data 是未定义的,它返回一个空对象。

感谢帮助!

最佳答案

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

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

这会将值转换为字符串,如您预期的那样显示在控制台中。

关于javascript - Angular 2 Http get - 从响应中解析 JSON 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44854693/

相关文章:

java - 如何解决android中的Unterminated array Exception

javascript - 这两个请求之间的区别

javascript - 如何使用跨域 - javascript 从另一个域获取 JSON 文件?

Angular <router-outlet name ="popup"> 更改 URL 路径结构?

javascript - 为什么 "this"在粗箭头函数定义中未定义?

javascript - Html按钮不显示表单

angular - 输入中的值在 Angular 2 中未绑定(bind)

javascript - Angular 2/4 |类型 '{}' 不可分配给类型 'Object[]'

javascript - 根据倒计时改变div的颜色

javascript - if 语句逻辑未产生期望的结果