2017-04-14 107 views
0

我在將數據從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保存到數組?

+2

這是什麼意思,你不開心?你的問題不是很清楚。 – rakwaht

+0

爲什麼'JSON.stringify(id);'如果'id'是'3'它會產生''3「',而不是json ... – n00dl3

+0

看着這條服務線 .map((response)=> response.json().documents.document) 在我看來有更好的方法來解決它 – urqel

回答

0

服務

return this.http 
    .post(DOCUMENTS_URL, body, options) 
    .map((res: Response) => { 
    res.json().map((obj) => { 
     new Document(obj.id, obj.description, obj.date) 
    }) 
    }) 

這應返回的文檔的集合

0

我沒有看到你怎麼能拿過去

.map((response) => response.json().documents.document)

這僅僅是在您的陣列放置在響應期內。您必須對後端進行更改才能更改此設置。

我不理解的是爲什麼你在你的訂閱裏面做了不必要的迭代,爲什麼不直接分配來到你的documentsArray的數組呢?像這樣:

this.documentsService.downloadDocuments(id) 
    .subscribe(documents => { 
    if(documents != null) { 
     this.documentsArray = documents; 
    } 
});