gpt4 book ai didi

javascript - 获取 Angular 2 中的系统时间更改事件

转载 作者:行者123 更新时间:2023-12-02 13:52:44 26 4
gpt4 key购买 nike

我希望在系统时间发生变化时收到通知。比如早上 9 点到 10 点或者下午 5 点到 6 点。基本上在我的应用程序中,我想每小时更改一次显示。我知道我可以通过手动计算来获得零钱。我只是好奇是否有其他方法可以在系统时间自动更改时收到通知。

最佳答案

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

现场演示:https://plnkr.co/edit/QJCSnlMKpboteXbIYzqt?p=preview

关于javascript - 获取 Angular 2 中的系统时间更改事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40925805/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com