2016-12-02 7 views
0

システム時刻が変更されたときに通知を受けたいと考えています。午前9時から午前10時または午後5時から午後6時までのように。基本的に私のアプリケーションでは、時間単位で表示を変更したいと思います。私は手動で計算して変更を得ることができることを知っています。私はシステムタイムが自動的に変わるときに通知を受けることができるので、他の方法があるかどうか不思議です。角度2のシステム時間変更イベントを取得

答えて

2

サービス用にはangle2は用意されていませんが、あなた自身で作成することができます。ここで

は、それが行うことができる方法を実証するためのシンプルなサービスです。

@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

+0

わかりました。答えてくれてありがとう。 –

+0

時間が変更された場合、次のフル時間との差分を計算してから、その距離を秒単位でチェックするのではなく、その距離に設定できませんでしたか? –

+0

確かに、それはちょうど秒のデモのためです。 :)私はその行にコメントをします! – mxii

関連する問題