Angular RxJS 定时器工作不正常

Angular RxJS timer works not like it's supposed to

我遵循了这里的答案: I already have a timer implemented according to this answer: 我的解决方案显然只倒计时到 14:59 并卡在那里。如何解决这个问题?我的 HTML:

<p> {{ this.authenticationService.countDown$ | async | date:'mm:ss' }} </p>

将计时器更改为以下代码,现在它从 00:00 开始计数并立即跳到 59:59 并开始倒计时,但一段时间后它冻结在 00:00。应该是15分钟倒计时。我修改的代码:

 StartTimer() {
    this.countDown$ = merge(
      fromEvent(document, 'mousedown'),
      fromEvent(document, 'mousemove'),
      fromEvent(document, 'click'),
      fromEvent(document, 'keydown'),
      fromEvent(document, 'scroll')
    ).pipe(
      startWith(false),
      switchMap(_ => {
        // * 1000 to turn the number into miliseconds
        let counter = (15 * 60 * 1000) + 1;
        return timer(0, 1000).pipe(
          take(counter),
          // count down in ms!!
          map(_ => --counter * 1000),
          tap(null, null, () => {
            console.log('countdown complete');
            // redirect to login page
            window.location.href = 'http://IPHERE:8080/logout';
          })
        );
      })
    );

take中你使用的是毫秒,你需要在这里使用秒。 在 map 中,您从毫秒中减去 1,然后乘以 1000 得到微秒,您需要在此处提供正确的毫秒。

我会这样做:

switchMap(_ => {
  let counter = 15 * 60; // seconds
  return timer(0, 1000).pipe(
    take(counter + 1),
    // subtract the seconds that have past and turn the result into milliseconds
    map(t => (counter - t) * 1000),
    tap({
      complete: () => {
        console.log("countdown complete");
        // redirect to login page
        window.location.href = "http://IPHERE:8080/logout";
      }
    })
  );
})