如何破坏/停止可观察的时间间隔

德里克罗扎

我有一个倒计时计时器,在用户离开页面后,该计时器将继续运行。当用户离开页面时,我想破坏倒计时计时器的运行或停止它。我怎样才能做到这一点?

倒计时

public time: number;
public countDown:Observable<any>;
public currentUnix;

constructor() {
    this.currentUnix = moment().unix();
    this.time = moment(1503773977000).unix() - this.currentUnix;
}


ngOnInit() {
    this.countDown = Observable.interval(1000)
      .map(res => {
        return this.time = this.time - 1
      })
      .map(res => {

        let timeLeft = moment.duration(res, 'seconds');
        let string: string = '';

        // Days.
        if (timeLeft.days() > 0)
          string += timeLeft.days() + ' Days';

        // Hours.
        if (timeLeft.hours() > 0)
          string += ' ' + timeLeft.hours() + ' Hours';

        // Minutes.
        if (timeLeft.minutes() > 0)
          string += ' ' + timeLeft.minutes() + ' Mins';

        // Seconds.
        string += ' ' + timeLeft.seconds();
        console.log("string", string);
        return string;
      })
}
亚历山大·彼得罗夫斯基(Aleksandr Petrovskij)

您可以使用takeUntil运算符。

import { Subject } from 'rxjs/Subject';
import 'rxjs/add/operator/takeUntil';

...

private onDestroy$ = new Subject<void>();

ngOnDestroy(): void {
    this.onDestroy$.next();
}

ngOnInit() {
    this.countDown = Observable.interval(1000)
                               .takeUntil(this.onDestroy$) // <----
                               .map(
... 

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章