首先,我在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(表格)崩溃; ,但我不知道为什么 .
2 回答
由于Ionic使用 Type 脚本,因此了解声明属性类型和为属性赋值之间的区别非常重要 .
做
tables: any[]
你只是说tables
属性是any[]
类型的属性(所以是任何数组) . But you are not initializing that property, it's just undefined by now由于它未定义,当您尝试使用它调用
push
方法时,您会收到该错误 .要解决此问题,
tables
属性为空数组,以便您可以在其上调用push
方法:将此更改为