我在將數據從json推送到對象時遇到了問題。將數據從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保存到數組?
這是什麼意思,你不開心?你的問題不是很清楚。 – rakwaht
爲什麼'JSON.stringify(id);'如果'id'是'3'它會產生''3「',而不是json ... – n00dl3
看着這條服務線 .map((response)=> response.json().documents.document) 在我看來有更好的方法來解決它 – urqel