gpt4 book ai didi

angular - 以 Angular 显示时间/时钟

转载 作者:行者123 更新时间:2023-12-02 11:25:18 30 4
gpt4 key购买 nike

我正在使用以下方法在我的应用程序中显示时间?

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();
}
}
里面的component.html
Simple Clock:
<div>{{ time | date: 'hh:mm:ss a' }}</div>
RxJS Clock:
<div>{{ rxTime | date: 'hh:mm:ss a' }}</div>
工作 demo

关于angular - 以 Angular 显示时间/时钟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54289078/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com