【问题标题】:Ionic 2/3: Runtime Error: Property undefinedIonic 2/3:运行时错误:属性未定义
【发布时间】:2017-07-24 14:52:56
【问题描述】:

首先我在 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);
          }
        }
      ]
    });
}

当我在 Ionic 实验室测试应用程序并添加一个表时,它给了我错误:运行时错误 _this.tables 未定义。

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

【问题讨论】:

    标签: angular typescript ionic2 ionic3


    【解决方案1】:

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

    tables: any[] 你只是说tables 属性是any[] 类型的属性(所以是任何东西的数组)。 但您并没有初始化该属性,它现在只是未定义

    由于它是未定义的,当您尝试使用它调用 push 方法时,您会收到该错误。

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

    public tables: any[] = [];
    

    【讨论】:

    • 非常感谢!你是对的,我还在为打字稿而苦苦挣扎。谢谢你的帮助:)
    • 很高兴听到它有帮助:)
    • 我可以问你一个快速跟进的问题吗?我现在正试图在我的 HTML 文件中显示推送的值。所以我写了: #{{ tables.number }} Status: {{ tables.name }} list> 但不幸的是,这些值没有显示出来。推送数据后唯一打印的是“#Status:”。知道如何解决这个问题吗? :)
    【解决方案2】:
     tables: any[]
    

    把它改成

    tables: any=[];
    

    【讨论】:

      猜你喜欢
      • 2018-04-15
      • 1970-01-01
      • 2017-11-14
      • 1970-01-01
      • 2018-04-14
      • 2018-02-26
      • 1970-01-01
      • 2018-04-10
      • 1970-01-01
      相关资源
      最近更新 更多