Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 clock update every second

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!

like image 386
Christian Avatar asked Mar 13 '17 04:03

Christian


1 Answers

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);
like image 125
Nikhil Shah Avatar answered Oct 09 '22 23:10

Nikhil Shah