【问题标题】:RxJS: Progress bar with countdownRxJS:带倒计时的进度条
【发布时间】:2020-04-07 16:46:31
【问题描述】:

我正在尝试制作一个带有进度条的按钮,按钮下方的文本将告诉您还剩多少时间。我正在使用在 [0 ... 1] 之间取值的离子进度条。

public timeToClose = 5 * 1000;

...

const interval = this.timeToClose / 100;
    timer(0, interval).pipe(
      tap((v) => this.progress = v / 100),
      map(i => this.timeToClose - i * interval),
      take(100),
      tap((timeLeft) => this.timeLeft = Math.floor(timeLeft / 1000) + 1),
      finalize(() => this.closeModal()),
    ).subscribe();

但这看起来很糟糕。我怎样才能使它更好的代码?

【问题讨论】:

    标签: ionic-framework rxjs


    【解决方案1】:

    我会这样做:

    of(5).pipe( // <- time in seconds we want the delay.
        map(v => v * 1000),
        switchMap(delay => {
            const start = new Date().getTime();
            return timer(0, 250).pipe( // <- speed of updates.
                map(() => (new Date().getTime() - start) / delay),
                takeWhile(result => result < 1, true),
            );
        }),
        tap(v => this.progress = v), // <- your stuff
        finalize(() => this.closeModal()), // <- your stuff
    ).subscribe();
    

    【讨论】:

    • 谢谢。有趣的实现。
    • 谢谢,我什至会将它保留为可观察的,并使用异步管道在模板中订阅。因为 rx 的目标是保持数据在流中流动。
    【解决方案2】:

    我想建议一种不同的方法:

        // Total amount of steps
        const steps = 9;
        // Total "loading" time in milliseconds
        const totalTimeMs = 3000;
    
        interval(totalTimeMs / steps).pipe(
          take(steps), 
          map(step => step + 1), 
          tap(step => {
              const progressPercent = step / steps * 100;
              // update your progress bar
        })).subscribe();

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-20
      • 2020-12-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多