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

Viewed 4415

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.

1 Answers

You should tru something like this:

this._router.events.subscribe(event => {
    // ... yourcode
});
Related