我试图在一定的时间间隔(如2秒)后迭代数组的每个元素然后显示它。当我尝试这样做时它会成功控制日志,但当我尝试将其推入msg
时,为了实现我的目标,我得到一个ERROR TypeError: Cannot set property 'msg' of undefined at timer
是否有某些东西丢失或是更好的解决方案?
export class AuthPage {
public verifyPhone : string;
public collection = 'clients';
public data;
public user;
public response;
count : number;
msg : any[];
constructor(public navCtrl : NavController, public navParams : NavParams, public afs : AngularFirestore, public appService : AppServiceProvider, private alertCtrl : AlertController,) {
let messages=[
'Welcome to Fight Rabbit',
'We are going to ask you a few questions to help setup your account',
'What\'s your Phone Number?'
]
var interval = setInterval(function () {
timer()
}, 2000)
var count = 0;
function timer() {
this.msg=[];
if (count < messages.length) {
this.msg.push(messages[count])
console.log(messages[count],count)
count += 1
} else {
clearInterval(interval)
}
}
}
}
答案 0 :(得分:0)
最有可能是范围问题。
尝试用以下代码替换您的代码:
export class AuthPage {
msg : any[];
count = 0;
.......
constructor(public navCtrl : NavController, public navParams : NavParams, public afs : AngularFirestore, public appService : AppServiceProvider, private alertCtrl : AlertController,) {
const messages = [
'Welcome to Fight Rabbit',
'We are going to ask you a few questions to help setup your account',
'What\'s your Phone Number?'
]
const interval = setInterval(() => {
this.timer()
}, 2000)
this.count = 0;
}
timer() {
this.msg = [];
if (count < messages.length) {
this.msg.push(messages[count])
console.log(messages[count],count)
count += 1
} else {
clearInterval(interval)
}
}
}
答案 1 :(得分:0)
您收到错误无法设置属性msg未定义这意味着'this'关键字在您的功能块中未定义。 this关键字未在功能块中绑定
首先在你的函数中尝试console.log并检查它是否未定义,如果是,那么尝试使用es6 arrow函数语法或简单的hack:
timer() {
this.msg = [];
console.log(this) // if you get empty msg array then bind your this else bind it before the timer function starts(just above the timer())
let $this = this // use $this every where inside this block and it wont give you undefined error
if (count < messages.length) {
$this.msg.push(messages[count])
console.log(messages[count],count)
count += 1
} else {
clearInterval(interval)
}
}
答案 2 :(得分:0)
快速解决方法是:
export class AuthPage {
public verifyPhone : string;
public collection = 'clients';
public data;
public user;
public response;
count : number;
msg : any[];
constructor(public navCtrl : NavController, public navParams : NavParams, public afs : AngularFirestore, public appService : AppServiceProvider, private alertCtrl : AlertController,) {
let messages=[
'Welcome to Fight Rabbit',
'We are going to ask you a few questions to help setup your account',
'What\'s your Phone Number?'
]
var count = 0;
var interval = setInterval(() => {
this.msg=[];
if (count < messages.length) {
this.msg.push(messages[count])
console.log(messages[count],count)
count += 1
} else {
clearInterval(interval)
}
}, 2000)
}
}