Cannot read property “push” of undefined

余生长醉 提交于 2021-02-05 11:10:34

问题


I have an error when I try to push a value in an array. The mystic thing in this error is that it only occurs on the Ionic Dev App, whereas in the Google Chrome Console, everything works perfectly.

I did initialize the array, so the error doesn't come from here. Maybe, the error comes from an asynchronous operation, but I don't see where I don't catch a promise...

initModelesList(){
  this.addModele = this.navParams.get('addModele') || false;
  this.deleteModele = this.navParams.get("deleteModele") || false;
  if (!!this.addModele){
    this.modelesList.push(this.addModele); //error here
    this.saveModelesList();
  }
  if (!!this.deleteModele){
    const index: number = this.modelesList.indexOf(this.deleteModele);
    if (index !== -1){
      this.modelesList.splice(index,1)
    }
    this.saveModelesList()
  }
}
saveModelesList(){
 this.storage.set('modelesList',this.modelesList)
}
getModelesList(){
  this.storage.get('modelesList').then((modelesList) => {
    this.modelesList=modelesList;
    this.initModelesList()
  },()=>{
    this.modelesList=[];
    this.initModelesList();
  })
}

Here's a screenshot of the error on the Ionic Dev App.


回答1:


Make sure you have initialized modelesList

You can explicitly check if it's not null and create one if needed:

this.modelesList= this.modelesList|| [];


来源:https://stackoverflow.com/questions/50972246/cannot-read-property-push-of-undefined

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!