【问题标题】:why does ngOnInit() execute multiple times for setInterval()?为什么 ngOnInit() 为 setInterval() 执行多次?
【发布时间】:2021-04-12 10:39:34
【问题描述】:

我是 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() 会执行多次而不是一次?

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

【问题讨论】:

  • 也许您想使用 setTimeout 而不是 setInterval ? ngOnInit 被调用 1 次。问题出在逻辑上
  • 是的,也许setTimeoutngOnInit 执行一次。但是请解释一下为什么setIntervalngOnInit 执行多次?我正在寻找原因
  • 它不会多次执行 ngOninit.. 它会多次执行 setInterval 中的回调.. 也许你应该阅读一下 setInterval 是什么..?

标签: angular typescript ngoninit


【解决方案1】:

1000 = 1 seg,尝试增加值

【讨论】:

  • 但是你能解释一下为什么setIntervalngOnInit 执行多次吗?我正在寻找原因
  • 不是多次执行ngOnInit,间隔是在提供的时间段内重复的循环
猜你喜欢
  • 1970-01-01
  • 2019-08-01
  • 2021-11-25
  • 1970-01-01
  • 2019-06-28
  • 2018-06-13
  • 2014-07-23
相关资源
最近更新 更多