Angular2 clock update every second

Christian picture Christian · Mar 13, 2017 · Viewed 17.5k times · Source

I've followed the Tour of Heroes tutorial, and I'm now in the process of modifying the project. My project will have a lot of clocks and timers, and my first task is to make a clock that displays the UTC time. With the MomentModule, I'm able to display the time of the page load with:

<p>{{ myDate | amDateFormat: 'ddd Do HH:mm:ss' }}</p>

However, it doesn't update every second like I want it to.

My DashboardComponent looks like this:

export class DashboardComponent implements OnInit {
    heroes: Hero[] =[];
    myDate: Date;

    constructor(private heroService: HeroService) {}

    ngOnInit(): void {
        this.heroService.getHeroes()
            .then(heroes => this.heroes = heroes);

        this.utcTime();
    }

    utcTime(): void {
        setInterval(function() {
            this.myDate = new Date();
            console.log(this.myDate); // just testing if it is working
        }, 1000);
    }
}

So first of all, is it a good idea to create new Date(); every second? Either way, is there a way for update the time in my view every second through something like an observable or similar? Like I said, I'll have a lot of timers and clocks on my page when it's finished. Thanks!

Answer

micronyks picture micronyks · Mar 13, 2017

You just need to use arrowfunction instead of using a traditional function callback syntax as shown below,

setInterval(() => {         //replaced function() by ()=>
  this.myDate = new Date();
  console.log(this.myDate); // just testing if it is working
}, 1000);