如何在 Angular 中停止 setInterval

How do I stop setInterval in Angular

我有一个对象数组,我应该将数组的第一个树元素的 isChecked 属性 设置为 true。 array 索引为 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 来做。我为此创建了一个演示倒计时 link 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();

我建议使用 clearInterval 来停止 setinterval

请查看以下内容以实施