[英]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. 我正在尝试解析我的服务器API在向它发出HTTP get请求后返回的JSON对象。 Here is the call to the Http
这是对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. 当我记录this.payoutReport时,我可以在控制台中看到一个JS Object对象。 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).
当我在控制台中检查它时,我可以看到它具有我需要的JSON对象的所有属性(基本上这是我需要的对象)。 Except that it is a JS Object object, not the JSON object format I am looking for.
除了它是一个JS Object对象,而不是我正在寻找的JSON对象格式。
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. 但是,res.json()。数据是未定义的,它返回一个空对象。
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.
问题是console.log无法显示JSON对象...所以只需在控制台中显示“对象”。 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 使用以下代码,一个文件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 组件文件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.