代码之家  ›  专栏  ›  技术社区  ›  iJade

将JSON响应对象值分配给Angular模型类对象

  •  0
  • iJade  · 技术社区  · 5 年前

    我从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 from响应未映射到 empage 从模型实例中。如何在不使属性名称相同的情况下实现相同?

    预期产出:

    {empage: 12, firstName: "Sam", lastName: "Thomson"}
    
    1 回复  |  直到 5 年前
        1
  •  0
  •   Prashant Pimpale Dila Gurung    5 年前

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

    只需使用:

    Object.assign(emp, result, {empage: result.employeeAge});
    
        2
  •  0
  •   Michael D    5 年前

    有两件事要注意

    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