如何在不使用TypeScript(Angular 6)对其进行显式编码的情况下将json响应转换为对象? [英] How to convert json response into an object without explicitly coding it in TypeScript (Angular 6)?

查看:123
本文介绍了如何在不使用TypeScript(Angular 6)对其进行显式编码的情况下将json响应转换为对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的小项目中,部分功能是管理项目实体.我创建了一个看起来像这样的类:

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;
  }
}

这个想法是当我从API调用中获取项目列表时获得这些对象的列表.

获取列表的服务函数是:

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

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

我正在这样使用它(在控制器中):

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

我对这一切的期望是,我实际上将获得一个Project对象的列表.但是,控制器中的this.projects值是一个json对象数组,因此,在没有显式构建对象的情况下,我无法使用Project的任何功能.

有没有一种方法可以将json投射"/解析为对象以获得真实的对象? 怎么样?

解决方案

如注释中所述,http.get中的类型转换仅涉及返回对象的形状(即属性),而不涉及方法.

将这些仅属性对象之一转换为所需对象的实际实例以使用Object.assign的最简单方法,如Object.assign(new MyObject(), jsonObject)

例如,

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

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 (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)
      );

这篇关于如何在不使用TypeScript(Angular 6)对其进行显式编码的情况下将json响应转换为对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆