角无法读取未定义的遍历数组的属性

时间:2019-04-01 02:37:39

标签: angular typescript

我正在尝试以4秒的间隔无限遍历一个数组。它每4秒执行一次该功能,但是我在控制台中记录了以下内容:

  • wemadeit
  • 未定义
  • 错误TypeError:无法读取未定义的属性'undefined'
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')
    }
  }

}

2 个答案:

答案 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 = () => {};