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!

Christian
  • 195
  • 1
  • 2
  • 10
  • You can check my plunker example here http://plnkr.co/HaTd8q, I use rxjs to implement the timer library, source is in github https://github.com/J-Siu/ng2-simple-timer – John Siu Mar 13 '17 at 05:18

1 Answers1

22

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);
0mpurdy
  • 3,198
  • 1
  • 19
  • 28
micronyks
  • 54,797
  • 15
  • 112
  • 146
  • 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? – Christian Mar 13 '17 at 05:25
  • This is traditional javascript/typescript way. You can use `Rxjs` library for better implementation. – micronyks Mar 13 '17 at 05:34
  • 1
    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) – Simon_Weaver Jun 20 '17 at 19:37
  • 1
    @micronyks do you have a sample of the Rxjs version? – Simon_Weaver Jun 20 '17 at 19:38