问题
Is it possible for angular2 to return raw json response? Ex.
Component
getrawJson(){
this.someservice.searchJson()
.subscribe( somelist => this.somelist = somelist,
error => this.errorMsg = <any>error);
}
For service
searchJson(num: number, somestring: string, somestring2: string): Observable<stringDataObj> {
let body = JSON.stringify({"someJsonData"[{num, somestring, somestring2}]});
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
return this.http.post(URL, body, options)
.map(this.jsonObj)
.catch(this.handleError);
}
private jsonObj(res: Response) {
let body;
return body{ };
}
The above implementation returns Array . Will there be a way for me to get the raw json data returned by the service? I'm expecting to have json response like below
{ "dataParam": [ { "num": "08", "somestring": "2016-10-03", "somestring2": "2016-10-03" }], "someDatalist": [ { "one": "08", "two": 1, "three": "2016-10-03" }] }
Thanks!
回答1:
Yes off course you can !!
Actually angualar2 returns Response in the form of Observable
instead of promise Like in angular1.x , so in order to convert that observable into raw Json format we have to use the default method of angular2 i.e
res.json()
There are no of method apart from .json()
provided by angular which can be described here for more info.
methods include
- res.text()
- res.status
- res.statusText etc
https://angular.io/docs/ts/latest/api/http/index/Response-class.html
update
use your code like this
return this.http.post(URL, body, options)
.map(res => {return res.json()})
.catch(this.handleError);
}
回答2:
private jsonObj(res: Response) {
return res.json() || {} ;
}
来源:https://stackoverflow.com/questions/40136352/can-i-return-raw-json-response-in-angular2