将数据从JSON保存到对象

时间:2017-04-14 07:18:05

标签: json angular typescript rxjs observable

我将数据从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 个答案:

答案 0 :(得分:0)

<强>服务

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

这应该返回一个文档集合

答案 1 :(得分:0)

我没看到你怎么能过去

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

这就是您的数组放在响应期间的位置。您必须对后端进行更改才能更改此内容。

我不理解为什么你在订阅中进行不必要的迭代,为什么不直接分配到你documentsArray的数组呢?像这样:

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