简体   繁体   中英

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

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?

As mentioned in the comments, the typecast in your http.get just concerns the shape of the returned objects (ie 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)
      );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM