【问题标题】:Assign JSON response object value to Angular model class object将 JSON 响应对象值分配给 Angular 模型类对象
【发布时间】:2020-06-26 18:55:08
【问题描述】:

我从 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}

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

预期输出:

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

【问题讨论】:

  • 确保属性名称相同!尝试用employeeAge替换empage
  • 我正在寻找一种不使属性名称相同的方法
  • 试试这个:Object.assign(emp, this.data, {empage: this.data.employeeAge}));

标签: json angular api serialization


【解决方案1】:

您可以使用 Object.assign 方法的重载版本,它接受三个参数,您可以将第三个值作为要覆盖其值Reference link 的对象传递:

只需使用:

Object.assign(emp, result, {empage: result.employeeAge});

【讨论】:

    【解决方案2】:

    注意两点

    1. 在声明this.http.get('/api').subscribe((result: Employee) 中,假定响应为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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-05-22
      • 1970-01-01
      • 2021-05-29
      • 2018-12-21
      • 2018-12-20
      • 2020-06-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多