我想在系统时间更改时得到通知。例如上午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/

10-16 19:40
查看更多