angular - 如何在 Angular 中停止 setInterval
问题描述
我有一个对象数组,我应该将 isChecked 属性设置为 true 到数组的第一个树元素。数组索引为 3 后,我应该重定向到另一个页面,但 setInterval 仍在运行
public sendApplication(): void {
if (this.formService.isFormValid(this.formGroup)) {
this.dialogProcessing
= this.dialog.open(FoDialogBankVerificationComponent, {
width: '500px',
disableClose: true,
data: this.checkBoxValues,
});
this.submit()
.pipe(
take(1))
.subscribe(res => {
this.checkBoxValues.forEach((checkbox, index) => {
this.interval = interval(1000 * index).subscribe(() => {
checkbox.isChecked = true;
console.log(index);
if (res.id === 1700) {
if (index === this.checkBoxValues.length - 1) {
this.status = res.id;
this.dialogProcessing.close();
this.interval.unsubscribe();
}
} else {
const random: number = Math.floor(1 + Math.random() * 4);
if (index === random) {
this.dialogProcessing.close();
this.interval.unsubscribe();
this.navigationService.navigateToDeniedPage();
}
}
});
});
},
() => {
this.dialogProcessing.close();
this.notificationService.showGetErrorNotification();
});
}
}
解决方案
使用 observable 来做到这一点。我在链接https://stackblitz.com/edit/angular-gq9zvk中为此创建了一个演示倒计时
创建属性
ispause = new Subject();
timer: Observable<number>;
timerObserver: PartialObserver<number>;
启动计时器
this.timer.subscribe(this.timerObserver);
创建计时器
this.timer = interval(1000)
.pipe(
takeUntil(this.ispause) // take until used to stop it
);
this.timerObserver = {
next: (_: number) => {
//u cann call function here
}
};
停止 this.ispause.next();
推荐阅读
- google-sheets - 谷歌表格查询不返回值
- discord.js - 如何从在线广播中获取数据?
- python - 无法在 Windows 上使用 pypmml 加载 pmml 文件。获取 FileNotFoundError: [WinError 2] 系统找不到指定的文件
- javascript - 为什么我的 CSS 文件在 header.php 中不起作用?
- image-processing - 如何在imgaug中使用多个边界框进行批处理
- qt - LNK 2019 错误:Qt 项目在 MINGW 中工作,而不是在 MSVC 中
- python - 如何根据在另一个相应列中找到的值覆盖 pandas 中的列?
- angular - 如何在不使用 NgModel 的情况下使用 PrimeNg 将选定的复选框值传递给子组件?角
- python - 为什么 jupyter 服务器在 VS 代码中失败?
- amazon-web-services - 使用 python 将文件上传到 s3 存储桶会导致访问被拒绝