After searching for a suitable solution for Angular 8, I encountered various suggestions that were not satisfactory. Some methods resulted in infinite loops causing a stack overflow, while others seemed too makeshift for my liking. Fortunately, I came across an effective solution online which I will summarize here instead of sharing just a link. This solution allows customization for specific routes without the need for creating custom classes.
I found this solution from Simon McClive's article at
https://medium.com/engineering-on-the-incline/reloading-current-route-on-click-angular-5-1a1bfc740ab2
To implement this solution, start by adjusting your app-routing module configuration:
@ngModule({ imports: [RouterModule.forRoot(routes, {onSameUrlNavigation: ‘reload’})],
exports: [RouterModule] })
Then, modify the specific routes you wish to impact. If authentication is not required, you can exclude the canActivate parameter:
export const routes: Routes = [
{
path: ‘invites’,
component: InviteComponent,
children: [
{
path: ‘’,
loadChildren: ‘./pages/invites/invites.module#InvitesModule’,
},
],
canActivate: [AuthenticationGuard],
runGuardsAndResolvers: ‘always’, //choose 'always', 'paramsOrQueryParamsChange', or 'pathParamsChange'
}
]
Finally, update your component to listen for navigation events and respond accordingly (don't forget to unregister the listener when needed):
export class AwesomeComponent implements OnInit, OnDestroy{
// ... define your class variables here
navigationSubscription;
constructor( private router: Router ) {
// subscribe to the router events and store the subscription for future unsubscription
this.navigationSubscription = this.router.events.subscribe((e: any) => {
// Check for NavigationEnd event and re-initialize the component
if (e instanceof NavigationEnd) {
this.myInitFn();
}
});
}
myInitFn() {
// Reset any changes caused by route parameter modifications
// Perform data fetching, service calls, etc.
}
ngOnDestroy() {
// Clean up to prevent memory leaks
if (this.navigationSubscription) {
this.navigationSubscription.unsubscribe();
}
}
}