首页 > 解决方案 > 如何在 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();
                });
    }
}

标签: angularrxjssetinterval

解决方案


使用 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();


推荐阅读