Search code examples
timerrxjsangular7

rxjs timer in angular7


I've upgraded my project from cli 5 to cli 7 and I just encountered some issue

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
  }
}

seems like rxjs has changed a lot in angular 7 and I am having some problem converting this existing this.countDown to the newer version.

So I am not able to use Observable.timer anymore? how can I change this please?


Solution

  • When you upgraded your angular project from 5 to 7, rxjs is also upgraded to version 6. You can use this instead

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