How to handle Browser Refresh action on Angular 5?

天涯浪子 提交于 2021-01-27 04:25:10

问题


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 . . .
    }
  });

}


回答1:


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;
    }
});

}

reference from : https://stackblitz.com/edit/angular-r6-detect-browser-refresh



来源:https://stackoverflow.com/questions/48391760/how-to-handle-browser-refresh-action-on-angular-5

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!