angular7中的rxjs计时器

时间:2019-05-13 21:44:18

标签: 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
  }
}

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

所以我不能再使用Observable.timer了?我该如何更改?

1 个答案:

答案 0 :(得分:3)

将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))
        );
    }
 }