Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display Clock with Angular 6 and RxJs 6

How do I display a clock using rxjs 6 using Angular 6. The below code worked for angular 5. But now I am getting an error saying that interval is not of type Observable.

@Injectable()
export class MailService {

  private clock: Observable<Date>;


  constructor(private http : HttpClient) { 
    this.clock = Observable.interval(1000).map(tick => new Date()).share();
  }

  getClock(): Observable<Date> {
    return this.clock;
  }

}
like image 451
Abhishek Gangadhar Avatar asked Dec 18 '22 22:12

Abhishek Gangadhar


2 Answers

I would recommend some minor improvements to the given answers of Sachila and codeepic for these issues:

  1. The interval() operator emits its first value after the first period has past (see docs)
  2. With share() a subsequent subscription could miss the last tick and has to wait 1s until the next value arrives. This could lead to a delayed display response.

Solution:

  1. Using timer(0, 1000): "Its like interval, but you can specify when the emissions should start." (see docs)
  2. Using shareReplay(1), where 1 indicates the number of previously emitted values that are emitted on a new subscription

Code (Angular 6 with RxJS 6):

import { Injectable } from "@angular/core";

import { Observable, timer } from "rxjs";
import { map, shareReplay } from "rxjs/operators";

@Injectable({
  providedIn: "root"
})
export class ClockService {
  private _time$: Observable<Date> = timer(0, 1000).pipe(
    map(tick => new Date()),
    shareReplay(1)
  );

  get time() {
    return this._time$;
  }

  constructor() {}
}  

To access the time:

import { ClockService } from "PATH/clock.service";

constructor(private _clockService: ClockService) {
   this._clockService.time.subscribe((now: Date) =>
     console.log("time:", now.toISOString())
   );
}
like image 148
neox5 Avatar answered Dec 28 '22 10:12

neox5


from rxjs 6+ you have to use the interval operator.
if you are using operators use the pipe operators

import { interval } from 'rxjs';  
import { map, share } from 'rxjs/operators';

this.clock = interval(1000).pipe(  
    map(tick => new Date()),
    share()
)
like image 38
Sachila Ranawaka Avatar answered Dec 28 '22 11:12

Sachila Ranawaka