如何在不使用 setInterval() 的情况下在 angular 中显示当前时间
How to show current time in angular without using setInterval()
我想在angular 11.
中显示当前活动时间
我喜欢这个
setInterval(() => {
this.UKTime = formatDate(
Date.now(),
"dd-MM-yy hh:mm a",
"en-US",
"+0100"
);
this.SLTime = formatDate(
Date.now(),
"dd-MM-yy hh:mm a",
"en-US",
"+0530"
);
}, 1000);
但是我不需要定时器。
还有其他显示当前时间的方法吗?
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>
Working Demo
我想在angular 11.
中显示当前活动时间我喜欢这个
setInterval(() => {
this.UKTime = formatDate(
Date.now(),
"dd-MM-yy hh:mm a",
"en-US",
"+0100"
);
this.SLTime = formatDate(
Date.now(),
"dd-MM-yy hh:mm a",
"en-US",
"+0530"
);
}, 1000);
但是我不需要定时器。
还有其他显示当前时间的方法吗?
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>
Working Demo