Ionic 2/3: Runtime Error: Property undefined
首先我在 macOS 上使用 Ionic 3.x。
我正在尝试将一些数据推送到数组中。
在我定义的导出类中。
1
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
export class HomePage {
tables: any[] //… addTable(){ let prompt = this.alertCtrl.create({ |
当我在 Ionic 实验室测试应用程序并添加一个表时,它给了我错误:运行时错误
_this.tables 未定义。
会显示”成功”警报,因此应用程序在 this.tables.push(table); 处崩溃; ,但我不知道为什么。
由于 Ionic 使用 Typescript,因此了解声明属性类型和为属性赋值之间的区别非常重要。
做 tables: any[] 你只是说 tables 属性是 any[] 类型的属性(所以是任何东西的数组)。但是您没有初始化该属性,它只是现在未定义
因为它是未定义的,当你尝试使用它调用 push 方法时,你会得到那个错误。
要解决这个问题,请将 tables 属性初始化为一个空数组,这样您就可以在其上调用 push 方法:
1
|
public tables: any[] = [];
|
- 非常感谢你!你是对的,我还在为typescript而苦苦挣扎。谢谢您的帮助 :)
- 很高兴听到它有帮助:)
- 我可以问你一个快速跟进的问题吗?我现在正试图在我的 HTML 文件中显示推送的值。所以我写了: <ion-list> <ion-item *ngFor=”let table of tables”> #{{ tables.number }} Status: {{ tables.name }} </ion-item> </ion- list> 但不幸的是,这些值没有显示出来。推送数据后唯一打印的是”#Status:”。知道如何解决这个问题吗? :)
1
|
tables: any[]
|
把它改成
1
|
tables: any=[];
|
来源:https://www.codenong.com/45269972/