简体   繁体   中英

Typescript Array push only show latest item

I have a list get from my API, like as :

{
  "content": [
    {
      "trainingClassId": 1,
      "examCode": "my exam 1",
      "address": {
        "addressId": 1,
        "addressValue": "abc 1213"
      },
      "description": "only test",
      "classId": null,
      "startDate": 1511110800000,
      "endDate": 1513702800000,
     "examDate": 1511542800000

    },
    {
      "trainingClassId": 2,
      "examCode": "my exam 2",
      "address": {
        "addressId": 1,
        "addressValue": "abc 1213"
      },
      "description": "only test",
      "classId": null,
      "startDate": 1511110800000,
      "endDate": 1513702800000,
     "examDate": 1511542800000
    }
  ],
  "last": true,
  "totalElements": 2,
  "totalPages": 1,
  "size": 20,
  "number": 0,
  "first": true,
  "sort": null,
  "numberOfElements": 2
}

I want to convert long to date, so I create 1 object to binding data:

export class myApp {
    id: number;
    classId: string;
    trainingDate: string;
    examDate: string;

}

on my ts:

listData = new Array();

  app_unit:myApp= new myApp();
  listApp:any[];

ngOnInit() {
    this.getAllTrainingClass();

  }
 async getAllTrainingClass(): Promise<void>{
     await this.traningClassService.getdata().then(data =>this.listApp = data);

     for(let ls of this.listApp){


        this.app_unit.classId= ls.classId;
        this.app_unit.examDate=this.convertTimestampToDate(ls.examDate);
        this.app_unit.trainingDate=this.convertTimestampToDate(ls.startDate) +'-'+this.convertTimestampToDate(ls.endDate) ;

       this.listData.push(this.app_unit);


     }

the console log of has 2 item, but it is the latest item, like as:

{0:myApp id:2 classId:null examDate:"05/01/2018" trainingDate:"05/11/2017-31/12/2017" }, {1:myApp id:2 classId:null examDate:"05/01/2018" trainingDate:"05/11/2017-31/12/2017"}

please advice me.

The problem is because "this.app_unit" is pointing to the same memory location, you are inserting the same object into the array, all pointing to the same memory location.

Put,

  var app_unit:myApp= new myApp(); 

inside the for loop. Thus, a new instance of the object is created with each loop.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM