我可以在angular2中返回原始json响应吗 [英] Can I return raw json response in angular2
问题描述
angular2是否有可能返回原始的json响应?例
Is it possible for angular2 to return raw json response? Ex.
组件
getrawJson(){
this.someservice.searchJson()
.subscribe( somelist => this.somelist = somelist,
error => this.errorMsg = <any>error);
}
服务
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{ };
}
以上实现返回Array.我有办法获取服务返回的原始json数据吗?我期望像下面这样的json响应
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":[{ 一个":"08", 两个":1, 三":"2016-10-03" }] }
{ "dataParam": [ { "num": "08", "somestring": "2016-10-03", "somestring2": "2016-10-03" }], "someDatalist": [ { "one": "08", "two": 1, "three": "2016-10-03" }] }
谢谢!
推荐答案
可以,当然可以!
实际上,angualar2以Observable
的形式返回Response,而不是angular1.x中的promise,因此,为了将可观察的结果转换为原始Json格式,我们必须使用angular2的默认方法,即
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()
除了由角度提供的.json()
之外,没有其他方法可以在此处进行介绍,以获取更多信息.
There are no of method apart from .json()
provided by angular which can be described here for more info.
方法包括
- res.text()
- res.status
- res.statusText 等等
- 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);
}
这篇关于我可以在angular2中返回原始json响应吗的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!