我希望在系统小时更改时收到通知。喜欢从上午9点到10点或下午5点到下午6点。基本上在我的应用程序中,我想每小时更改显示。我知道我可以通过手动计算来获得更改。我只是好奇有没有其他办法,所以当系统时间自动改变时我会收到通知。
答案 0 :(得分: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);
}
}