Search code examples
angularangular-routing

Angular 8 router does not fire any events with `onSameUrlNavigation: 'reload'` when trying to activate the same route


Router config:

imports: [
    RouterModule.forRoot(routes, {
      onSameUrlNavigation: 'reload',
      scrollPositionRestoration: 'top'
    })
  ],

My route:

  {
    path: 'orders',
    loadChildren: './modules/order/order.module#OrderModule',
    canLoad: [OrderGuard],
    runGuardsAndResolvers: 'always'
  },

Then in my forchild:

 {
        path: 'new-order',
        component: NewOrderComponent,
        pathMatch: 'full',
        canActivate: [OrderGuard],
        runGuardsAndResolvers: 'always'
      },

In my actual component:

 this.routerSubscription = this.router.events.subscribe(event => {
      console.log('NAVIGATION EVENT', event);
      if (event instanceof NavigationEnd) {
        console.log('NAVIGATION END');
        this.ngOnDestroy();
        this.initializeComponent();
      }
    });

No events whatsoever trigger after trying to re-activate the same route. Events do show up for the initial activation though.

EDIT: The guards do indeed get triggered.

EDIT: my ngOnDestroy code messing things up:

 if (this.routerSubscription) {
      this.routerSubscription.unsubscribe();
    }

Solution

  • Unfortunately onSameUrlNavigation only executes guards and resolvers, and it does not reinitialize components.

    A good part is that it does triggers navigation thus you have 2 approaches to follow

    You can use the Events from the RouterModule to handle this as

    constructor(private _router: Router) {}
    
    ngOnInit() {
      this._router.events.subscribe(res => {
        if (res instanceof NavigationEnd) console.log("NavigationEnd Event");
      });
    }
    

    OR

    You can pass a random number in the router navigation method and subscribe to that parameter to execute your logic

    Stackblitz at https://stackblitz.com/edit/angular-route-reload

    Edit:

    As pointed out in my comment, it seems that there is something going on in the ngOnDestroy method and it seems like you might be unsubscribing to your route events subscription while calling ngOnDestroy. The fiddle is updated to show this scenario.

    This would not only execute your routing events just once.