我正在尝试以4秒的间隔无限遍历一个数组。它每4秒执行一次该功能,但是我在控制台中记录了以下内容:
export class TechnologiesComponent implements OnInit {
public slideInState: String = 'in';
public test1Show: Boolean = true;
public test2Show: Boolean = false;
private counter: number = 0;
private imgArray: Array<boolean> = [false, false, false, false];
constructor() { }
ngOnInit() {
setInterval(this.imgCycle, 4000);
}
imgCycle() {
console.log('wemadeit')
console.log(this.counter)
console.log(this.imgArray[this.counter])
this.imgArray[this.counter] = true;
if (this.counter == this.imgArray.length) {
this.counter = 0
console.log('reset')
} else {
this.counter++
console.log('+1')
}
}
}
答案 0 :(得分:1)
imgCycle
方法在Angular区域之外运行,因为setInterval是浏览器api。将其更改为箭头方法将解决此问题。示例:
imgCycle = () => {
console.log('wemadeit')
console.log(this.counter)
console.log(this.imgArray[this.counter])
this.imgArray[this.counter] = true;
if (this.counter == this.imgArray.length) {
this.counter = 0
console.log('reset')
} else {
this.counter++
console.log('+1')
}
}
答案 1 :(得分:1)
这不是一个特别的问题。您的 this
实际上不是this
。运行setTimeout
时的上下文是不同的。当您运行setTimeout
时,实际上是在运行window.setTimeout()
,因此当您引用this
时,实际上是在引用window
对象。不会有imgCycle()
方法。解决此问题的方法很少。
1。使用bind()
:
ngOnInit() {
setInterval(this.imgCycle.bind(this), 4000);
}
imgCycle() {}
2。使用箭头功能:
这需要您将imgCycle
更改为方法变量
ngOnInit() {
setInterval(this.imgCycle, 4000);
}
imgCycle = () => {};