首页 > 解决方案 > 为什么 ngOnInit() 会为 setInterval() 执行多次?

问题描述

我是 Angular 的初学者。

export class CountComponent implements OnInit {

  public no:number;

  constructor() { 
     this.no=0;
  }

  public myfun():void{
     this.no++;
     alert(this.no);
  }

  ngOnInit(): void {
     this.myfun();
  }
}

当我运行上面的代码时,alert() 只弹出一次。这意味着 ngOnInit() 只执行一次。但

export class CountComponent implements OnInit {
  public no:number;

  constructor() { 
    this.no=0;
  }

  public myfun():void{
      setInterval(()=>{
        this.no++;
        alert(this.no);
      },1000);
  }
 
  ngOnInit(): void {
    this.myfun();
  }
}

当我运行上面的代码时,alert() 反复弹出。这意味着 ngOnInit() 连续执行多次(或 myfun() 执行多次)。

所以我的问题是,当我在 myfun() 添加 setInterval() 时,为什么 ngOnInit() 执行多次而不是一次?

如果已经问过这个问题,请给我完整的解释并原谅我。

标签: angulartypescriptngoninit

解决方案


1000 = 1 seg,尝试增加值


推荐阅读