Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to proceed correctly in angular when the user reloads the page with f5?

Tags:

I am new at Angular 2-4 and right now I am having problems when the page is reloaded with f5. As I have seen, the problem is that I am navigating towards the same route and therefore the ngOnInit() is not loaded again. In the ngOnInit() is where I initialize some of the variables and dynamic forms that I use. I have seen a possible solution that is to subscribe to the parameters of the route and there call a method that initializes everything. Something like this:

this.activeRoute.params.subscribe(
params => {
   this.paramX = params['paramX'];
   this.initializeComponent();
});

private initializeComponent() {

}

  Is that the correct way to do it? Is that a good practice or should I do it in another way? Thanks in advance.

like image 827
Ridel Hernández Infante Avatar asked Oct 30 '17 19:10

Ridel Hernández Infante


1 Answers

To formalize my comment: if you use the browser's refresh/reload, or Location.reload() to refresh any page on an angular application, you do run ngOnInit() again, and all other life-cycle hooks.

This is because you are reloading the entire application from scratch, all the way down to platformBrowserDynamic().bootstrapModule(AppModule) and then re-bootstrapping everything. That's what refresh does.

If you need a demonstration, open Developer Tools and set a breakpoint in your Component's ngOnInit() and hit refresh. You will stop at the breakpoint.

The phrasing in your later comment "enters the same route" presumes that there is already a known route. There is not, because the application is entirely re-bootstrapped.

You may be thinking of calling router.navigate([...]) to your present location with identical path parameters. This will not emit a NavigationStart event and the router will not attempt to load anything (because why would it, you haven't navigated anywhere). That, in turn, will not call ngOnInit().

That said, yes, the way you are currently handing path parameters is the best solution, chiefly because it allows you to react to changes in the path without forcing you to reinitialize the Component.

Put another way, if all of your Component logic relies on the dynamic path parameter being set OnInit, what happens if the parameters changes after the component is instantiated? Nothing.

like image 103
msanford Avatar answered Sep 23 '22 12:09

msanford