angular7 中的 rxjs 计时器

bbu*_*ver 1 timer rxjs angular7

我已经将我的项目从 cli 5 升级到 cli 7,但我遇到了一些问题

import { Component, Input, Output, OnInit, EventEmitter } from '@angular/core'
import { Observable, Subscription } from 'rxjs/Rx';

@Component({
  selector: 'countdown',
  template: '{{ countDown | async | formatTime }}'
})
export class CountdownComponent implements OnInit {
  @Input() seconds: string;
  @Output() checkTime: EventEmitter<number> = new EventEmitter();
  countDown: any;

  constructor() {}

  ngOnInit() {
    const start = parseInt(this.seconds, 10);
    this.countDown = Observable.timer(0, 1000)
                .map(i => start - i) // decrement the stream's value and return
                .takeWhile(i => i >= 0)
                .do(s => this.checkTime.emit(s)) // do a side effect without affecting value
  }
}
Run Code Online (Sandbox Code Playgroud)

似乎 rxjs 在 angular 7 中发生了很大变化,我在将现有this.countDown版本转换为较新版本时遇到了一些问题。

所以我不能再使用Observable.timer了吗?请问这个怎么改?

小智 5

当您将 angular 项目从 5 升级到 7 时,rxjs 也会升级到版本 6。您可以改用它

import { Component, Input, Output, OnInit, EventEmitter } from '@angular/core';
import { timer, Observable } from 'rxjs';
import { map, takeWhile, tap } from 'rxjs/operators';

@Component({
  selector: 'countdown',
  template: '{{ countDown | async | formatTime }}'
})
export class CountdownComponent implements OnInit {
   @Input() seconds: string;
   @Output() checkTime: EventEmitter<number> = new EventEmitter();
  countDown: any;

  constructor() {}

  ngOnInit() {
    const start = parseInt(this.seconds, 10);
    this.countDown = timer(0, 1000).pipe(
        map(i => start - i),
        takeWhile(i => i >= 0),
        tap(s => this.checkTime.emit(s))
        );
    }
 }
Run Code Online (Sandbox Code Playgroud)