rxjs6 计时器未在 Angular 6 中触发,订阅可观察到的计时器已投入使用

rxjs6 Timer not being triggered in Angular 6 subscription to observable timer placed in service

我正在尝试将来自 rxjs 6 的计时器放入 angular 6 服务中。而且它没有被触发。我没有运气就查看了文档。这是我的服务代码(只有相关部分:

import { map,flatMap, catchError, take } from 'rxjs/operators';
import { BehaviorSubject, of, throwError,timer, Observable } from "rxjs";

.....

  countdownTimer = new Observable<number>();


  formatCountdownTime(count) {
    const seconds = count % 60 < 10 ? '0' + Math.floor(count % 60) : Math.floor(count % 60);
    /*    if(count <= 1000){
         //set timer to NOT RUNNING state so it updates UI components like the button that depends on the count
          this.contributorManagerService.countdownTimerIsRunning.next(false);
       } */
       return Math.floor(count / 60) + ':' + seconds;
  }

  createCountdownTimerObservable(count){
    this.countdownTimer =  timer(0, 1000);

  }

这是计时器的消耗。我需要知道时间何时过去,这就是我将第三个函数参数传递给订阅的原因,因为我需要在时间到时启用一个按钮。

import { map,take } from 'rxjs/operators';


export class CampaignDataComponent implements OnInit, OnDestroy {

 countdownTimerIsRunning = false ;
 count: number;


ngOnInit(){

/* I subscribe to the timer and the 3rd parameter indicates what to do when time has elapsed */
      this.sharedHelpersService.countdownTimer.
      pipe(
        take(this.count),
        map(() => {
          --this.count;

          return this.count;
        })
      ).subscribe(count=>{
        console.log("New count",count);

          if(count>0){
             this.countdownTimerIsRunning = true;
          }
      },
      err=>{
        console.log("Countdown timer error", err);
      },
      ()=>{
        console.log("Time has elapsed");
        this.countdownTimerIsRunning = false;
      });

}

}

你知道为什么没有被触发吗?当我在组件上使用整个链时它曾经工作,但由于我需要从其他组件使用它,我不得不将它放在服务中并且破坏了它。有任何想法吗?。非常感谢您

编辑:澄清一下,所有组件都应该消耗相同的倒计时

当你说你需要使用其他组件的倒计时时,如果你的意思是你需要使用其他组件的功能,但订阅的每个组件都有自己独立的倒计时,那么你可以这样做以下:

服务:

import { timer, Observable } from 'rxjs';
import { filter, takeWhile, map } from 'rxjs/operators';

// startTime is in seconds
count(startTime: number): Observable<number> {
  return timer(0, 1000).pipe(
    takeWhile(t => t < startTime),
    map(t => startTime - t)
  )
}

组件:

// Count down for 10 seconds.
countdownService.count(10).subscribe(
  t => console.log(t), 
  null, 
  () => console.log('Done!')
)

这将打印:10 9 8 7 6 5 4 3 2 1 完成!

这个代码有问题

  pipe(
    take(this.count),
    map(() => {
      --this.count;

      return this.count;
    })

我假设组件中没有其他代码,所以 this.count 初始化为 0。然后您订阅可观察对象并有效地说 take(0),然后可观察对象立即完成。

以下应该可以让多个组件共享计时器:

服务:

import { Injectable } from '@angular/core';
import { timer, Subject, Observable } from 'rxjs';
import { takeWhile, map } from 'rxjs/operators';

@Injectable()
export class CountdownService {

  private _countdown = new Subject<number>();

  countdown(): Observable<number> {
    return this._countdown.asObservable();
  }

  private isCounting = false;

  start(count: number): void {
    // Ensure that only one timer is in progress at any given time.
    if (!this.isCounting) {
      this.isCounting = true;
      timer(0, 1000).pipe(
        takeWhile(t => t < count),
        map(t => count - t)
      ).subscribe(
        t => this._countdown.next(t),
        null,
        () => {
          this._countdown.complete();
          this.isCounting = false;
          // Reset the countdown Subject so that a 
          // countdown can be performed more than once.
          this._countdown = new Subject<number>();
        }
        );
    }
  }
}

一个组件可以用

启动倒计时
countdownService.start(myCountdownTime)

所有对倒计时时间感兴趣的组件都可以订阅

countdownService.countdown().subscribe(t => ...)

Stackblitz Example