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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With