首页 > 解决方案 > 将 JSON 响应对象值分配给 Angular 模型类对象

问题描述

我从 API 收到以下响应。

{
    'firstName' : 'Sam',
    'lastName' : 'Thomson',
    'employeeAge' : 12 
}

在我的 Angular 代码中,我试图将 JSON 响应映射到 Angular 类模型。这是类模型。

export class Employee{
    constructor(){
        this.empage = 0;
    }
    public firstName : String;
    public lastName : String;
    public empage : Number;
}

这是API调用的代码。

this.http.get('/api').subscribe((result : Employee) =>{
      let emp = new Employee();
      Object.assign(emp, result);
      console.log('Result is ', emp);
    })

收到的输出是:

{empage: 0, firstName: "Sam", lastName: "Thomson", age: 12}

如上所示,agefrom 响应没有empage从模型实例映射到。如何在不使属性名称相同的情况下实现相同的目标?

预期输出:

{empage: 12, firstName: "Sam", lastName: "Thomson"}

标签: jsonangularapiserialization

解决方案


需要注意的两件事

  1. 在声明this.http.get('/api').subscribe((result: Employee)中,响应被假定为 type Employee,而事实并非如此。最好换成result: any.
  2. 据我所知,没有本地方法可以将一种类型的对象映射到另一种类型。以下是针对您的特定要求的解决方法Object.keys()
export class AppComponent implements OnInit  {
  private employeeMap = ((source): Employee => {
    const result = new Employee();
    Object.keys(source).map((key) => {
      if (key === 'employeeAge') {
        result['empage'] = source[key];
      } else {
        result[key] = source[key];
      }
    });
    return result;
  });

  ngOnInit() {
    this.jsonService.getData().subscribe(
      (result: any) => {
        let emp: Employee = this.employeeMap(result);
        console.log(emp);
      }
    );
  }
}

工作示例:Stackblitz


推荐阅读