Home > Software engineering >  Angular append query parameter to the same route
Angular append query parameter to the same route

Time:05-24

I have the following Route setup in my app.routing.module

const routes: Routes = [
  { path: "", redirectTo: "/smart-parking/dashboard", pathMatch: "full" },
  { path: "locations-create", component: AddLocationComponent, canActivate: [AuthGuard] },
  { path: "smart-parking", loadChildren: () => import('./smartparking/smartparking.module').then((m => m.SmartParkingModule)), canActivate: [AuthGuard] },
// more routes here
]

"smar-parking" routing module is the following:

 [

  {
    path: "", component: SidenavComponent,
    children: [
      {path: "", redirectTo: "dashboard", pathMatch:"full"},
      { path: "dashboard", component: DashboardComponent },
      { path: "insights", component: InsightsComponent},
      { path: ":organization/gateways/:id", component: GatewayComponent },
      { path: "setup/devices", component: SetupDevicesComponent}
    ]
  },
  
];

When I navigate to /smart-parking/dashboard on of the components is running the following code:

this.router.navigate(
  ['.'],
  {
    relativeTo: this.route.parent,
    queryParams: queryParams,
    skipLocationChange: true,
    queryParamsHandling:"merge"
  }
)

Generally I want to append a query parameter in the url withougt changing the url. The problem is that it redirects me to the following url /dashboard?queryparm=value instad of /smart-parking/'dashboard?queryparam=value. I am thinking it has something to do with using dashboard as a children of smart-parking but cannot explain nor solve it. Any ideas?

CodePudding user response:

There was an issue related to this that was caused when lazy loaded modules were being used

A fix was added, relativeLinkResolution - might be worth trying. The Angular team added it as a config option so it wouldn't be a breaking change

@NgModule({
  imports: [RouterModule.forRoot(routes, {
    relativeLinkResolution: 'corrected'
  })],
  exports: [RouterModule]
})
export class AppRoutingModule { }

CodePudding user response:

What worked for me is to go with the following:

this.router.navigate(
    ['.'],
    {
        relativeTo: this.route.firstChild,
        queryParams: queryParams,
        queryParamsHandling: "merge"
    }
)

I am not sure this is the correct solution. Any ideas would be nice.

  • Related