rxjs 6 倒数计时器订阅 angular 6

rxjs 6 countdown timer subscribe angular 6

我尝试在 angular 6 中使用 rxjs 6 实现倒数计时器。我还需要能够订阅结果并重置计时器:

我尝试了什么:

var timer =  interval(1000).pipe(
take(4)
);
timer.subscribe(x => console.log(x));

结果:

0
1
2
3

我需要的是反转定时器从 3 数到 1

我找到了这个倒计时函数来实现反向计数,但我无法订阅它,就像第一个例子

 interval(1000).pipe(
 map((x) => { console.log( x) })
  );

结果:

您可以使用计时器而不是间隔,要真正实现倒计时,您应该像这样映射计时器结果:map(i => countdownStart - i)

  const countdownStart = 3;

  Rx.Observable
    .timer(1000, 1000)
    .map(i =>  countdownStart - i)
    .take(countdownStart + 1)
    .subscribe(i => console.log(i));

日志: 3个 2个 1个 0

另一种可能的解决方案是使用范围运算符。

Rx.Observable
  .range(0, countdownStart + 1)
  .map(i => countdownStart - i)
  .subscribe(i => console.log(i));

日志: 3个 2个 1个 0

下面是我使用 TimerObservable 的方法。记得在销毁时取消订阅。

import {TimerObservable} from "rxjs/observable/TimerObservable";
import { Subscription } from 'rxjs';

export class MyComponent implements OnInit, OnDestroy {

    private sub: Subscription;

    ngOnInit() {
        // Delay 0 seconds, run every second
        let timer = TimerObservable.create(0, 1000);

        let number = 3;

        this.sub = timer.subscribe(t => {
            if(number !== 0) {
               console.log(number);
               number--;
            }
        });
    }

    ngOnDestroy(): void {
        this.sub.unsubscribe();
    }
}

怎么样?

var timer =  interval(1000).pipe(
  take(4),
  map(x => 3 - x)
);
timer.subscribe(console.log);