我能够使用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
}
为了实现标签焦点,我使用了以下代码:
@HostListener('window:focus')
onFocus(event: FocusEvent): void {
this.fetchNewData()
}
问题是,仅当我在网页上单击事件时,才会触发onFocus
方法。我如何在没有用户点击网页的情况下检测到onFocus
?
我的想法是,您将在第一时间将时间存储在本地存储中。并且每隔下一次,您需要对当前时间和存储的过去时间进行求差。
ngOnInit() {
if (local storage.getItem("time") {
// Will execute this if block if time is available in local storage
// Difference between past time and current
interval = localStorage.getItem("pastTime") - getMilliSeconds(hrs, min, sec)
setInterval(this.timeOut(), interval);
} else {
// Will come here when no interval in local storage.
interval = getMilliSeconds(hrs, min, sec)
local storage.setItem("pastTime", interval)
}
}
超时功能,
timeOut() {
// Call your data
localStorage.setItem("time", getMilliSeconds(hrs, min, sec));
}
要获取,毫秒:
getMilliSeconds (hrs, min, sec) {
return((hrs*60*60+min*60+sec)*1000);
}
希望您了解发生了什么。在初始化时,我们将首次设置本地存储值。而且每次,我们都会在本地存储值和当前时间之间进行求差。并将该差异发送到setInterval()。这个时间我没有电脑。因此,这一切都无需计算机即可完成。如果您遇到问题,那一定是小问题,可以解决。