My goal is to display the live server time in my application. To achieve this, I created a component that utilizes the RXJS 'interval' function to update the time every second. However, this approach triggers the Change Detection routine every second!
Is there a way to update the time without causing change detection to run?
Below is the code for my component:
server-time.component.ts:
export class ServerTimeComponent implements OnInit {
serverTime: Date;
serverDatetime: InfoDatetime;
constructor(private infoService: InfoService) {}
ngOnInit() {
this.getServerDate();
// Increase time by interval
interval(1000).subscribe(() => {
// Skip if the time is not ready
if (this.serverTime === undefined) {
return;
}
// Update the time
this.serverTime = new Date(this.serverTime.getTime() + 1000);
// If it's midnight, get the date again
if (
this.serverTime.getHours() === 0 &&
this.serverTime.getMinutes() === 0 &&
this.serverTime.getSeconds() < 2
) {
this.getServerDate();
}
});
}
getServerDate() {
this.infoService
.getServerDatetime()
.subscribe((res: ApiResponse<InfoDatetime>) => {
if (res.code === 1) {
this.serverDatetime = res.data;
// Create a new Date. Time part will be used
this.serverTime = new Date('2000-01-01 ' + this.serverDatetime.time);
}
});
}
}
server-time.component.html:
<span *ngIf="serverDatetime">
<span class="ml-1">{{serverTime | date:'hh:mm:ss'}}</span>
—
<span class="mr-1">{{serverDatetime?.date_jalali}}</span>
</span>
To view the issue in action on stackblitz.io, click on the link below:
Thank you