Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 6 ngOnInit not firing when clicking browser's back button

I'm having problems with routes that involve parameters. When I try to go back with the browser's back button the ngoninit of the previous component doesn't fire.

Steps to reproduce the error with the angular's tutorial:

  • Download the tutorial from https://angular.io/tutorial and run npm install
  • Build the app with the command ng build --prod --build-optimizer or ng build --prod
  • Upload the static files generated by the previous step to an nginx or apache server with the respective configuration file having the recomended lines of code in angular docs. https://angular.io/guide/deployment
  • Click one of the top heros in the dashboard.
  • Click browser's back button.

By following those steps you will see the top heros are not loaded in the dashboard which is exactly the same problem I'm having with my app. This is be cause ngOnInit is not called when going back specifically with the back button.

A few things to note:
This problem only occurs while using Firefox, Chrome or Opera.
This problem doesn't accurs while using development mode ng serve.
I updated to angular 7 and still have the same issue.

Is there any way I could solve this problem? I didn't find anything about this in angular's repo issues.

like image 696
Robert Avatar asked Oct 26 '18 23:10

Robert


People also ask

How does function ngOnInit () will get invoked?

ngOnInit()link A callback method that is invoked immediately after the default change detector has checked the directive's data-bound properties for the first time, and before any of the view or content children have been checked. It is invoked only once when the directive is instantiated.

How do I call ngOnInit again?

ngOnInit() is called once for every method. There is no way to make it being called multiple times.

What is the difference between ngOnInit () and constructor () of a component?

The constructor() should only be used to initialize class members but shouldn't do actual "work". So we should use constructor() to setup Dependency Injection, Initialization of class fields etc. ngOnInit() is a better place to write "actual work code" that we need to execute as soon as the class is instantiated.


1 Answers

You should tru something like this:

this._router.events.subscribe(event => {
    // ... yourcode
});
like image 130
Raviteja V Avatar answered Nov 04 '22 07:11

Raviteja V