Angular2 clock update every second
Asked Answered
A

1

7

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!

Acrylic answered 13/3, 2017 at 4:24 Comment(1)
You can check my plunker example here plnkr.co/HaTd8q, I use rxjs to implement the timer library, source is in github github.com/J-Siu/ng2-simple-timerMweru
A
21

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);
Addis answered 13/3, 2017 at 4:36 Comment(4)
Thank you! As for the new Date() every second, is that going to clog up memory? Or is it a reasonable way to track time?Acrylic
This is traditional javascript/typescript way. You can use Rxjs library for better implementation.Addis
the reason this fixes the problem is that with a 'traditional callback' the value of this is not the parent object but instead is probably window. So it's like you're doing window.myDate Adding the arrow function allows the compiler to replace this with _this which is a reference to the parent (the object that contains myDate property)Perreault
@Addis do you have a sample of the Rxjs version?Perreault

© 2022 - 2024 — McMap. All rights reserved.