Angular Ionic 2/3:运行时错误:属性未定义

Angular Ionic 2/3:运行时错误:属性未定义,angular,typescript,ionic2,ionic3,Angular,Typescript,Ionic2,Ionic3,首先,我在macOS上使用了Ionic 3.x 我想把一些数据放到一个数组里 在导出类中,我定义了它 export class HomePage { tables: any[] //... addTable(){ let prompt = this.alertCtrl.create({ title: 'Add Table', subTitle: 'Enter the table number', inputs: [{

首先,我在macOS上使用了Ionic 3.x

我想把一些数据放到一个数组里

在导出类中,我定义了它

export class HomePage {
   tables: any[]
   //...
   addTable(){

    let prompt = this.alertCtrl.create({
      title: 'Add Table',
      subTitle: 'Enter the table number',
      inputs: [{
        name: 'tableNumber',
        placeholder: 'Number',
        type: 'number'
      }],
      buttons: [
        {
          text: 'Cancel'
        },
        {
          text: 'Add',
          handler: data => {
            let table = {
              number: data.tableNumber,
              name: 'occupied'
            }
            alert('Success');
            this.tables.push(table);
          }
        }
      ]
    });
}
当我在爱奥尼亚实验室测试应用程序并添加一个表时,它给出了一个错误:运行时错误 _此.tables未定义

显示“成功”警报,因此应用程序在此.tables.push(table)处崩溃,但我不知道为什么

 tables: any[]
将此更改为

tables: any=[];

由于Ionic使用Type脚本,因此了解声明属性类型和为属性赋值之间的区别非常重要

执行
tables:any[]
您只是说
tables
属性是
any[]
类型的属性(所以是任意数组)但是您没有初始化该属性,它只是现在还没有定义

因为它是未定义的,所以当您尝试使用它调用
push
方法时,会出现该错误

要解决此问题,
tables
属性初始化为空数组,这样您就可以对其调用
push
方法:

public tables: any[] = [];

非常感谢你!你说得对,我还在努力打字。谢谢你的帮助:)很高兴听到这个消息:)我可以问你一个快速的后续问题吗?我现在尝试在HTML文件中显示推送的值。所以我写了:{{tables.number}}状态:{{{tables.name}},但不幸的是,这些值没有显示出来。推送数据后唯一打印的内容是“#状态:”。知道如何解决这个问题吗?:)