Angular2 update hours every second

I followed the Tour of Heroes training course and am now in the process of modifying the project. My project will have many hours and timers, and my first task is to create a clock displaying UTC time. Using MomentModule I can display page load time with

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

However, it does not update every second as I want.

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, it's nice to create a new Date (); every second? In any case, is there a way to update the time in my view every second through something like observable or the like? As I said, I will have many timers and hours on my page when it ends. Thank!

+4
source share
2

arrowfunction function callback, ,

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

:

ngOnInit() {
  this.todayDate = setInterval( () => { 
         this.todayDate = new Date(); 
  }, 1000);
}
-1

Source: https://habr.com/ru/post/1672128/


All Articles