angular - 为什么 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() 执行多次而不是一次?
如果已经问过这个问题,请给我完整的解释并原谅我。
解决方案
1000 = 1 seg,尝试增加值
推荐阅读
- python - 无法使用 Scrapy 获取表数据
- r - 通过突变一些变量并保持一些变量与以前相同,将宽数据转换为 long
- python - 在不阻塞 Pygame UI 的情况下录制声音
- python-3.x - 将唯一值列表添加到现有 DataFrame 列
- laravel - 在 Laravel 7 中配置 PhpRedis
- oauth-2.0 - OAuth 令牌,限制 API 使用
- azure-devops - 在 Azure 开发操作中使用 UniversalPackage@0 任务发布成功且没有错误,但工件源中不存在包
- python - pytest - 使用仅在运行时计算的参数对测试进行参数化
- erlang - Erlang:异常错误:读取文本文件时右侧值{error,enoent}不匹配
- swift - Swift Google Maps 未进入安全区域