0
我希望在系统小时更改时得到通知。从上午9点到上午10点或下午5点到6点。基本上在我的应用程序中,我想按小时更改显示。我知道我可以通过手动计算来获得更改。我只是好奇有没有其他方式,以便系统小时自动更改时我可以得到通知。在Angular 2中获取系统小时更改事件
我希望在系统小时更改时得到通知。从上午9点到上午10点或下午5点到6点。基本上在我的应用程序中,我想按小时更改显示。我知道我可以通过手动计算来获得更改。我只是好奇有没有其他方式,以便系统小时自动更改时我可以得到通知。在Angular 2中获取系统小时更改事件
没有建立服务的angular2,但你可以创建自己的。
下面是一个简单服务来演示如何可以做到:
@Injectable()
class TimeNotifyService {
private _lastHour;
private _lastMinute;
private _lastSecond;
public hourChanged = new Subject<number>();
public minuteChanged = new Subject<number>();
public secondChanged = new Subject<number>();
constructor() {
setTimeout(() => this.timer(), 2000); // just a delay to get first hour-change..
}
private timer() {
const d = new Date();
const curHour = d.getHours();
const curMin = d.getMinutes();
const curSec = d.getSeconds();
if (curSec != this._lastSecond) {
this.secondChanged.next(curSec);
this._lastSecond = curSec;
}
if (curMin != this._lastMinute) {
this.minuteChanged.next(curMin);
this._lastMinute = curMin;
}
if (curHour != this._lastHour) {
this.hourChanged.next(curHour);
this._lastHour = curHour;
}
// timeout is set to 250ms JUST to demonstrate the seconds-change..
// if only hour-changes are needed, there is NO reason to check that often ! :)
setTimeout(() => this.timer(), 250);
}
}
好。谢谢你的回答。 –
难道你不能只计算下一个整小时的差异,然后将超时设置为该距离,而不是每小时检查4次,如果小时已更改? –
当然,它只是为了秒演示。 :)我会对该行发表评论! – mxii