如何使用 RxJS 和 Angular 制作 5 分钟倒计时器

mag*_*arm 1 rxjs angular

倒计时应该从 4:59,4:58,....0:00 开始。我试过这个:

export class CounterComponent {
  @Input() since!: number
  readonly timeToShow$ = timer(0, 1000).pipe(
    map(() => Math.floor((Date.now() / 1000 - this.since) / 60)),
  )
}
Run Code Online (Sandbox Code Playgroud)
<span *ngIf="((timeToShow$ | async) || 0) > 0; else recentlyAdded">
    {{ timeToShow$ | async }} Minute{{ (timeToShow$ | async) === 1 ? '' : 's' }}
  </span>
Run Code Online (Sandbox Code Playgroud)

但这给了我从今天开始经过的时间。我只需要 5 分钟倒计时。

Biz*_*Bob 10

要创建一个在 300 秒内每秒发出递减整数的 observable,您可以执行以下操作:

  secondsRemaining$ = timer(0, 1000).pipe(
    map(n => 300 - n),
    takeWhile(n => n >= 0),
  );

  // emits: 300, 299, 298 ... 0
Run Code Online (Sandbox Code Playgroud)

timer- 以指定的间隔发出递增的整数

map- 用于将增加的数字反转为剩余时间

takeWhile- 当满足条件时完成可观察的


如果我们使用毫秒而不是秒,我们可以使用 Angular 的date管道来很好地格式化时间:

<p> 
  {{ timeRemaining$ | async | date:'mm:ss' }}      <!-- ex: 03:47 -->
</p>
Run Code Online (Sandbox Code Playgroud)

要将其放入将持续时间作为 an 的组件中@Input(),它可能看起来像这样:

export class CountDownComponent {

  @Input() seconds = 300;

  timeRemaining$ = timer(0, 1000).pipe(
    map(n => (this.seconds - n) * 1000),
    takeWhile(n => n >= 0),
  );

}
Run Code Online (Sandbox Code Playgroud)

这是一个有效的StackBlitz演示。

  • 完美,并且没有具有数百个依赖项的库。简单又方便,谢谢你,节省了我的时间 (2认同)