首页 > 解决方案 > 如何在angular7中存储多个json对象

问题描述

如何将多个json对象存储到angular7中的数组中?

我正在尝试保存 json 对象数组,如下所示:

employees: any;

 ngOnInit() {
    this.getemployee().subscribe 
    data => this.employees == data,
    );
}

以下是我从后端得到的响应:

(32) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
0: {id: "59744", employee_name: "Sample API ", employee_salary: "18000", employee_age: "20", profile_image: ""}
1: {id: "59747", employee_name: "Test", employee_salary: "123", employee_age: "456", profile_image: ""}
2: {id: "59748", employee_name: "hello#amdon", employee_salary: "10000", employee_age: "35", profile_image: ""}
.......

标签: angular7

解决方案


创建以下结构的对象数组。

  //response  data structure
   export class ResponseData {
     id:string
     employee_name: string;
     employee_salary: string; 
     employee_age: string;
     profile_image:string;
   }

组件.ts

export class Test implements OnInit { 

 responseData:ResponseData[]=[]; 

 constructor(){ }

 ngOnInit() {
    this.getemployee().subscribe((data)=>{
       if(data != null) {
       console.log('response received');
       this.responseData = data;
       }
    });   
  }
}

推荐阅读