打字稿数组只显示最新项目

时间:2017-11-24 18:16:03

标签: javascript angular typescript

我有一个从我的API获取的列表,如:

{
  "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
}

我想将long转换为long,所以我创建了一个绑定数据的对象:

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

}

on 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);


     }

控制台日志有2个项目,但它是最新的项目,如:

{0:对myApp ID:2 CLASSID:空 examDate:&#34; 05/01/2018&#34; trainingDate:&#34; 05/11 / 2017-31 /二千零十七分之十二&#34; }, {1:对myApp ID:2 CLASSID:空 examDate:&#34; 05/01/2018&#34; trainingDate:&#34; 05/11 / 2017-31 /二千零十七分之十二&#34;}

请告诉我。

1 个答案:

答案 0 :(得分:1)

问题是因为&#34; this.app_unit&#34;指向相同的内存位置,您将相同的对象插入到数组中,所有对象都指向相同的内存位置。

Put,

  var app_unit:myApp= new myApp(); 
在for循环中

。 因此,每个循环都会创建一个新的对象实例。