Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle Browser Refresh action on Angular 5?

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

}

like image 345
Yukun Avatar asked Jan 22 '18 23:01

Yukun


People also ask

What happens when page is refreshed in Angular?

An Angular application is a single-page application, and in the context of a single-page application the full app is loaded once, and data or screens are refreshed as the user uses your application. A browser refresh is the equivalent of shutting down your application and launching it again.

How do you check if the page is refreshed in Angular?

If you want to detect the browser refresh with Angular, i will show you a simple way to do it. You need to look at the Angular Router. Specifically to the navigated property. This property is false when the router starts and after the first navigation it changes to true .

How do I stop Angular refresh?

You cannot prevent page refresh. The browser user can always hit F5. The "onbeforeunload" approach will allow you to warn the user, but you can't prevent it.

How do you refresh a component from another component in Angular 6?

Technically, we do this by feeding the new value in Subject, by just calling next(newValue) , and then it can be sent to all Observers who then need to subscribe it. Taking an example where a message - a string is sent/updated by one component and the other component needs to listen to it and receive/update the same.


1 Answers

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

like image 61
Manoj Mittha Avatar answered Oct 06 '22 19:10

Manoj Mittha