Angular2时钟每秒更新一次

时间:2017-03-13 04:24:03

标签: angular angular-moment

我已经按照英雄之旅教程,我现在正在修改项目。我的项目将有很多时钟和计时器,我的第一个任务是制作一个显示UTC时间的时钟。使用MomentModule,我能够显示页面加载的时间:

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

然而,它并不像我想要的那样每秒更新一次。

我的DashboardComponent看起来像这样:

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);
    }
}

首先,创建新的Date()是个好主意;每一秒?无论哪种方式,有没有办法通过像观察或类似的东西每秒更新我的视图中的时间?就像我说的那样,当我完成时,我的页面上会有很多计时器和时钟。谢谢!

3 个答案:

答案 0 :(得分:14)

您只需使用 arrowfunction ,而不是使用传统的 function callback 语法,如下所示,

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

答案 1 :(得分:0)

export class DateComponent implements OnInit {
  dateMessage : String;

  constructor() {

  setInterval(() => {         
    let currentDate=new Date();
    this.dateMessage = currentDate.toDateString()+' '+ currentDate.toLocaleTimeString();
  }, 1000);
}

答案 2 :(得分:-1)

工作原理:

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