url changes but angular does not navigate

Viewed 4466

I have 2 links like below. When I click on any one the first time, it navigates to it but when I click on the second link after that, the url changes but it does not navigate to it.

<li><a routerLink="/order/buyer" >Buyer</a></li>
<li><a routerLink="/order/seller">Seller</a></li>

These are my route configuration:

app.routing.module.ts

const routes: Routes = [
    {
        path: '',
        pathMatch: 'full',
        component: RootComponent,
    },
    {
        path: '',
        children: [
            {
                path: 'order',
                loadChildren: './order/order.module#OrderModule',
            }
        ]
    }

order.module.ts

export const ROUTES: Routes = [
    {
        path: ':orderParty/:id',
        component: OrderDetailComponent,
        canDeactivate: [OrderDetailGuardService]
    },
    {
        path: ':orderParty',
        component: OrderListComponent
    }
];  

Tried several things, that out there but didn't work. What I have noticed is on the second click, the ngOnInit() of the 'OrderListComponent' does not get called.

2 Answers

You have a few options to solve this common issue in Angular, the most common one is using the solution on this GitHub thread: https://github.com/angular/angular/issues/13831#issuecomment-319634921

constructor(private router: Router){
     // override the route reuse strategy
     this.router.routeReuseStrategy.shouldReuseRoute = function(){
        return false;
     }

     this.router.events.subscribe((evt) => {
        if (evt instanceof NavigationEnd) {
           // trick the Router into believing it's last link wasn't previously loaded
           this.router.navigated = false;
           // if you need to scroll back to top, here is the right place
           window.scrollTo(0, 0);
        }
    });

}

Another solution would to subscribe to your router params and handle change based on the new param like this article suggests:

this.activeRoute.params.subscribe(routeParams => {
        this.loadUserDetail(routeParams.id);
    });

https://medium.com/@mvivek3112/reloading-components-when-change-in-route-params-angular-deed6107c6bb

Yes, because route is same its the dynamic parameter that is changing. to read changed parameter you can inject router in construct and read parameter like

this.router.params.subscribe((params)=>{console.log(params)});

The route is pointing to same component hence its not re initializing.

Related