首页 > 解决方案 > 如何在 Angular 7 中停止间隔?

问题描述

我有一个连续发出值的函数。

我想要的是??

如果满足 Math.sign 条件,我会将用户重定向到另一个屏幕并显示一条 toast 消息。

但是现在,吐司消息是连续显示的,因为间隔是连续的。

我试过什么?

this.subscription.unsubscribe()内部if(Math.sign)条件,但它没有工作。

关于如何在以下代码中停止间隔的任何建议?

startTimer(validUntil: string) {
    this.counter$ = interval(1000).pipe(
        map((x) => {
            this.diff = Math.floor((new Date(validUntil).getTime() - new Date().getTime()) / 1000);

            if (Math.sign(this.diff) == -1) {
                //Tried this.subscription.unsubscribe() here

                // Redirects me to another component
                this.goBack(true);
            }
            return x;
        }));

    this.subscription = this.counter$
        .subscribe((x) => {
            this.message$ = this.dhms(this.diff);
        });
}


goBack(requestExpired: boolean) {
    if (requestExpired == true) {
        this.messageDialogService.presentToast('Expired')
    }
    this.router.navigate(['mypage']);
}

标签: angularrxjs

解决方案


恕我直言,takeWhile内部条件是最明显的方法。

例如:

startTimer(validUntil) {
  this.counter$ = interval(1000).pipe(

    // turn value emissions into diffs
    map(() => Math.floor((new Date(validUntil).getTime() - new Date().getTime()) / 1000)),

    // this is needed to terminate when condition is met
    takeWhile(diff => Math.sign(diff) !== -1),

    // when terminated on conditions -- navigate back
    finalize(()=>{
      this.goBack(true);
    })

    // just in case if user navigates out before condition is met
    takeUntil(this.destroy$)
  )
  .subscribe(diff => {
    this.message$ = this.dhms(diff);
  });
}

注意:然而,我怀疑你counter$根本不需要。您只能使用message$带有异步管道的流,例如

控制器

startTimer(validUntil) {
  this.messages$ = interval(1000).pipe(
    // ...
  )
}

模板

<div>{ messages$ | async }</div>

希望这可以帮助


推荐阅读