将可观察到的嵌套对象映射到另一个对象

时间:2020-03-22 18:50:56

标签: angular typescript rxjs

我需要将响应JSON中的子对象的字段映射到父对象

我收到以下答复

{
  "id": 1,
  "name": "file-1",
  "survey": {
    "identifier": 1,
    "displayedValue": survey-1
  }
}

我正在尝试将先前的json映射到该对象

import { Entity } from './entity';

export class File extends Entity {
    name: string;
    survey: Entity['identifier'];
    status: string;
}

这是实体类

export class Entity {
    displayedValue: string;
    identifier: string;
}

这是我尝试映射的方式

this.fileService.getFileById(this.fileId).subscribe(data => {
  this.file = data;
});

文件服务方法

  public getFileById(fileId: string): Observable<File> {
    const getFileByIdURL = environment.backendBaseURL + 'files/' + fileId;
    return this.http.get<File>(getFileByIdURL);
  }

我需要file.survey来包含调查标识符

1 个答案:

答案 0 :(得分:1)

只需按如下所示进行映射,

this.fileService.getFileById(this.fileId).subscribe(data => {
  const entity = new Entity();
  entity.displayedValue = data.survey?.displayedValue;
  entity.identifier= data.survey?.identifier;

  this.file = new file();
  this.file.survey = entity;
  this.file.status= 'what u want';
});