2017-04-14 108 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; 
    } 
});