How to convert json response into an object without explicitly coding it in TypeScript (Angular 6)?

别说谁变了你拦得住时间么 提交于 2019-12-24 10:48:01

问题


In my little project, part of the functionality is to manage project entities. I created a class that looks like this:

export class IdRef {
  id: number;
}

export class Project {
  id?: number;
  title: string;
  background?: string;
  problemStatement?: string;
  owner: IdRef;
  createdBy: IdRef;
  dateCreated: string;
  updatedBy?: IdRef;
  lastUpdated?: string;

  getDateCreated(): Moment {
    return moment(this.dateCreated);
  }

  getLastUpdated(): Moment {
    if (this.lastUpdated) {
      return moment(this.lastUpdated);
    }

    return undefined;
  }
}

The idea is to get a list of these objects when I fetch a list of projects from API call.

The service function that fetches the list is:

public getProjects(): Observable<Project[]> {
    const projectListUrl = `/v1/api/project`;

    return this.http.get<Project[]>(environment.apiDomain + projectListUrl)
      .pipe(
        catchError(this.networkService.handleError)
      );
  }

And I am using it like that (in a controller):

loadProjects() {
    this.projectService.getProjects()
      .subscribe(
        (projects: Project[]) => {
          console.log(`fetched ${projects.length} projects`);
          this.projects = projects as Project[];
        },
        error => this.error = error
      );
  }

The expectation that I had from all this, is that I will actually get a list of Project objects; however, the value of this.projects in the controller is an array of json objects instead, so there is no way I can use any functions of Project without building the objects explicitly.

Is there a way to "cast"/parse json into an object to get a real object? How?


回答1:


As mentioned in the comments, the typecast in your http.get just concerns the shape of the returned objects (i.e. the properties), not the methods.

The easiest way to convert one of these property-only objects to an actual instance of the desired object it to use Object.assign, as in Object.assign(new MyObject(), jsonObject)

So, for instance,

return this.http.get<Project[]>(environment.apiDomain + projectListUrl)
      .pipe(
        map(jsonObj => Object.assign(new Project(), jsonObj),
        catchError(this.networkService.handleError)
      );


来源:https://stackoverflow.com/questions/51229861/how-to-convert-json-response-into-an-object-without-explicitly-coding-it-in-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!