【问题标题】:Saving data from JSON to object将数据从 JSON 保存到对象
【发布时间】: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); 如果id3 它将产生"3",而不是json...
  • 在 service .map((response) => response.json().documents.document) 中查看这一行,我认为有更好的方法来解决它

标签: json angular typescript rxjs observable


【解决方案1】:

服务

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

这应该返回一个文档集合

【讨论】:

    【解决方案2】:

    我不知道你怎么能过去

    .map((response) =&gt; response.json().documents.document)

    这正是您的数组放置在响应中的位置,句号。您必须对后端进行更改才能更改此设置。

    我不明白的是,为什么您在订阅中进行不必要的迭代,为什么不直接将即将到来的数组分配给您的 documentsArray?像这样:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-09-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-30
      • 2011-09-11
      • 1970-01-01
      • 2017-06-22
      相关资源
      最近更新 更多