【发布时间】:2017-09-10 10:43:09
【问题描述】:
我在将数据从 json 推送到对象时遇到问题。
这个解决方案对我有用,但我对它不满意。看服务。 有没有更好的方法将此 json 中的数据保存到对象?
我从服务器获取的 json 如下所示:
{"documents": {"document": [
{
"id": 1,
"description": "Lorem ipsum",
"date": "2017-03-01"
},{
"id": 2,
"description": "Lorem ipsum",
"date": "2017-04-01"
}
]}}
我的服务:
downloadDocuments(id: number): Observable<DocumentsDTO[]>{
let headers = new Headers();
headers.append('Content-Type', 'application/json');
headers.append('Authorization', this.authorizationService.basic);
let options = new RequestOptions({headers: headers});
let body = JSON.stringify(id);
return this.http
.post(DOCUMENTS_URL, body, options)
.map((response) => response.json().documents.document)
}
以及我调用此服务的组件:
documentsArray: Array<DocumentsDTO>;
downloadUserDocuments(id: number) {
this.documentsService.downloadDocuments(id)
.subscribe(documents =>{
if(documents !=null){
this.documentsArray = [];
documents.forEach((data) => {
this.documentsArray.push(data);
});
}
});
}
此解决方案适用于我,但我对 . 有没有更好的方法将这个 json 中的数据保存到数组中?
【问题讨论】:
-
不开心是什么意思?你的问题不是很清楚。
-
为什么
JSON.stringify(id);如果id是3它将产生"3",而不是json... -
在 service .map((response) => response.json().documents.document) 中查看这一行,我认为有更好的方法来解决它
标签: json angular typescript rxjs observable