[Fixed] Display time/clock in angular

Issue

I am using below method to display time in my app?

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);
  }

this code is working fine but after some time application getting crashed.
is there any alternative way to display time in angular4/5/6?

Solution

Inside component.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();
    }
  }

Inside component.html

Simple Clock:
<div>{{ time | date: 'hh:mm:ss a' }}</div>
RxJS Clock:
<div>{{ rxTime | date: 'hh:mm:ss a' }}</div>

Working demo

Leave a Reply

(*) Required, Your email will not be published