import { Component, OnInit } from '@angular/core';
import { Subscription, timer } from 'rxjs';
import { map, share } from "rxjs/operators";
import { OnDestroy } from '@angular/core';
@Component({
selector: 'app-clock',
templateUrl: './clock.component.html',
styleUrls: ['./clock.component.scss']
})
export class ClockComponent implements OnInit, OnDestroy {
date: Date = new Date();
constructor() {
}
time = new Date();
rxTime = new Date();
intervalId;
subscription: Subscription;
ngOnInit() {
this.intervalId = setInterval(() => {
this.time = new Date();
}, 1000);
this.subscription = timer(0, 1000)
.pipe(
map(() => new Date()),
share()
)
.subscribe(time => {
this.rxTime = time;
});
}
ngOnDestroy() {
clearInterval(this.intervalId);
if (this.subscription) {
this.subscription.unsubscribe();
}
}
}
Simple Clock:
<div>{{ time | date: 'hh:mm:ss a' }}</div>
RxJS Clock:
<div>{{ rxTime | date: 'hh:mm:ss a' }}</div>