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;
}
}
I would recommend some minor improvements to the given answers of Sachila and codeepic for these issues:
interval()
operator emits its first value after the first
period has past (see docs)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:
timer(0, 1000)
: "Its like interval, but you can specify when the emissions should start." (see docs)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())
);
}
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()
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With