问题描述
我是 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() 执行多次而不是一次?
如果已经问过这个问题,请给我完整的解释并原谅我。
解决方法
1000 = 1 seg,尝试增加值