Angular 如何每1小时刷新一次页面中的数据,以及当选项卡以角度接收焦点时

Angular 如何每1小时刷新一次页面中的数据,以及当选项卡以角度接收焦点时,angular,typescript,focus,onfocus,Angular,Typescript,Focus,Onfocus,我能够使用interval和Subscription在Angular中每小时实现一次自动刷新 代码如下: ngOnInit() { const source = interval(3600000); // Refresh Every 1 hour this.subscription = source.subscribe(val => this.fetchNewData()); } fetchNewData () { // Fetch New data and

我能够使用
interval
Subscription
在Angular中每小时实现一次自动刷新

代码如下:

ngOnInit() {

   const source = interval(3600000); // Refresh Every 1 hour 
   this.subscription = source.subscribe(val => this.fetchNewData());

}


fetchNewData () {

    // Fetch New data and bind it to the View
} 
为了实现tab focus,我使用了以下代码:

@HostListener('window:focus')
onFocus(event: FocusEvent): void {
   this.fetchNewData()
}  
问题是,
onFocus
方法只有在我在网页上进行单击事件时才会触发。
如何在用户不点击网页的情况下检测
onFocus

我的想法是,您将首先将时间存储在本地存储器中。每下一次,您都需要对存储的当前时间和过去时间执行差分

ngOnInit() {
     if (!local storage.getItem("pastTime") {
         startTime = getMilliSeconds(hrs, min, sec)
        local storage.setItem("pastTime", startTime)
     }
     interval = localStorage.getItem("pastTime") - getMilliSeconds(hrs, min, sec)
    setInterval(this.timeOut(), interval);
}
在超时功能中

timeOut() {
    // Call your data
    localStorage.setItem("pastTime", getMilliSeconds(hrs, min, sec));
    // Changing your pastTime in above statement. Since, you want to continue it every one hour. 
    interval = localStorage.getItem("pastTime") - getMilliSeconds(hrs, min, sec)
    setInterval(this.timeOut(), interval);
}
要获取,以毫秒为单位:

getMilliSeconds (hrs, min, sec) {
    return((hrs*60*60+min*60+sec)*1000);
}
希望你明白发生了什么。在init上,我们将第一次设置本地存储值。每次,我们都会执行本地存储值和当前时间之间的差异。这个差异被发送到setInterval()。一旦你调用timeOut(),我们将在本地存储中再次设置pastTime,然后设置setInterval()。此时我没有电脑。所以,这一切都是在没有电脑的情况下完成的。如果你遇到一些问题,那一定是一些小问题,可以解决