app.component.ts
export class AppComponent implements OnInit, OnDestroy {
rxTime = new Date();
intervalId;
subscription: Subscription;
ngOnInit() {
// Using RxJS Timer
this.subscription = timer(0, 1000)
.pipe(
map(() => new Date()),
share()
)
.subscribe(time => {
let hour = this.rxTime.getHours();
let minuts = this.rxTime.getMinutes();
let seconds = this.rxTime.getSeconds();
//let a = time.toLocaleString('en-US', { hour: 'numeric', hour12: true });
let NewTime = hour + ":" + minuts + ":" + seconds
console.log(NewTime);
this.rxTime = time;
});
}
ngOnDestroy() {
clearInterval(this.intervalId);
if (this.subscription) {
this.subscription.unsubscribe();
}
}
}
app.component.html
RxJS Clock:
<div>{{ rxTime | date: 'hh:mm:ss a' }}</div>
工作演示