我正在使用以下方法在我的应用程序中显示时间?
constructor(private datePipe: DatePipe) {}
ngOnInit() {
this.getTime();
this.date = this.datePipe.transform(new Date(), "dd/MM/yyyy");
}
getTime() {
setInterval(() => {
this.time = this.datePipe.transform(new Date(), "HH:mm:ss");
this.getTime();
}, 1000);
}
这段代码工作正常,但一段时间后应用程序崩溃了。
有没有其他方法可以在 angular4/5/6 中显示时间?
内部组件.ts
time = new Date();
rxTime = new Date();
intervalId;
subscription: Subscription;
ngOnInit() {
// Using Basic Interval
this.intervalId = setInterval(() => {
this.time = new Date();
}, 1000);
// Using RxJS Timer
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();
}
}
内部组件.html
Simple Clock:
<div>{{ time | date: 'hh:mm:ss a' }}</div>
RxJS Clock:
<div>{{ rxTime | date: 'hh:mm:ss a' }}</div>
Working demo https://stackblitz.com/edit/angular-ihpcnz
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)