运行 打卡 Angular 4.3

running clock in Angular 4.3

我想要一个 运行 时钟(数字)在我的一个 Angular 4.3 应用程序上。

我为此尝试了很多研发,但没有成功。

也没有参考 angular 滴答时钟。

所以我尝试添加基于 java 脚本的解决方案,但它也不起作用。

见下面的代码。

startTime() {    
  var today = new Date();
  var h = today.getHours();
  var m = today.getMinutes();
  var s = today.getSeconds();
  m = this.checkTime(m);
  s = this.checkTime(s);   

  var t = setTimeout(this.startTime, 500);
  this.clock = commonSetting.formatedDate(h + ":" + m + ":" + s); // this is the variable that I am showing on the front end.    
}

checkTime(i) {
  if (i < 10) { i = "0" + i };  // add zero in front of numbers < 10
  return i;
}

I don't even know this is good practice or not.

谁能帮我解决这个问题?

如果是我,我会使用Moment.js,在组件的constructor()中设置一个间隔函数,每秒更新clock属性。然后你可以相应地在整个组件中显示时钟属性。

组件

constructor() {
    // Runs the enclosed function on a set interval.
    setInterval(() => {
        this.clock = moment().format('MMMM Do YYYY, h:mm:ss a');
    }, 1000) // Updates the time every second.
}

或者,您可以将基本时间戳保存到组件中的 属性,然后在前端使用管道,例如 Angular2-moment。我可能会走这条路,因为它为时钟 属性 提供了更大的灵活性,能够在别处重用它而不会过多地弄乱格式。

Angular2 矩管

{{ clock | amLocale:'en' | amDateFormat:'MMMM Do YYYY, h:mm:ss a' }}

之前我做的完全错了

现在,我的实际场景有下拉菜单,并且在每个下拉菜单更改事件中,我必须启动新时钟并且必须停止之前的时钟。

然后,我按照 JB Nizet 的评论,使用下面的代码实现了 运行 时钟。

TypeScript code

在导出中定义了一个全局日期变量 class。

time: Date;

然后在下拉的更改方法中,我添加了我的解决方案。

//get current date time, you can set your own Date() over here
var stationdate = new Date(date_from_dropdown_change);

//clear Interval, it's my system requirement
if(this.prevNowPlaying) {
    clearInterval(this.prevNowPlaying);
}

// set clock and Interval
this.prevNowPlaying  = setInterval(() => {         
    stationdate = new Date(stationdate.setSeconds(stationdate.getSeconds() + 1));
    this.time = stationdate;
}, 1000);

现在,this.Time 将每秒更新一次。

Html

<p class="localtime_p">{{ time | date:'MMM dd,yyyy HH:mm:ss'}}</p>

And currently it's working fine when I posted this answer..