问题描述
目前,我正在尝试检测浏览器刷新事件(使用 F5),然后重新初始化页面状态一次.我只是检查了路由器事件,即如果第一个事件类型是 NavigationStart 并且事件 id 是 1,我认为用户按下了浏览器刷新 F5 按钮.
Currently, I am trying to detect browser refresh event (with F5) and then re-initialize page state once. I simply checked the router events, i.e. if the first event type is NavigationStart and event id is 1, I think a user pressed browser Refresh F5 button.
示例代码如下所示.然而,看起来很奇怪.有没有更好的方法来归档相同的目标?或任何建议?谢谢
Sample code shown in below. However, it looks strange. are there any better way to archive the same goal? or any suggestions? thanks
export class AppComponent implements OnInit{
constructor(private router: Router) {
this.router.events.pairwise().subscribe((events: any[]) => {
if (events[0] instanceof NavigationStart
&& events[0].id === 1 && events[1].id === 1) {
// re-initialize page sate . . .
}
});
}
推荐答案
我尝试了以下代码来检查浏览器重新加载.
I tried below code to check browser reload.
构造函数(私有路由器:路由器){
constructor(private router: Router) {
this.subscription = router.events.subscribe((event) => {
if (event instanceof NavigationStart) {
browserRefresh = !router.navigated;
}
});
}
参考:https://stackblitz.com/edit/angular-r6-检测-浏览器-刷新
这篇关于如何处理 Angular 5 上的浏览器刷新操作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!