Angular2时钟每秒更新一次
发布时间:2020-12-17 06:50:49 所属栏目:安全 来源:网络整理
导读:我按照英雄之旅教程,我现在正在修改项目.我的项目将有很多时钟和计时器,我的第一个任务是制作一个显示UTC时间的时钟.使用MomentModule,我可以显示页面加载的时间: p{{ myDate | amDateFormat: 'ddd Do HH:mm:ss' }}/p 但是,它并不像我想要的那样每秒更新一
我按照英雄之旅教程,我现在正在修改项目.我的项目将有很多时钟和计时器,我的第一个任务是制作一个显示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()是个好主意;每一秒?无论哪种方式,有没有办法通过像观察或类似的东西每秒更新我的视图中的时间?就像我说的那样,当我完成时,我的页面上会有很多计时器和时钟.谢谢! 解决方法
你只需要使用arrowfunction而不是使用传统的函数回调语法,如下所示,
setInterval(() => { //replaced function() by ()=> this.myDate = new Date(); console.log(this.myDate); // just testing if it is working },1000); (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |