infodev
infodev

Reputation: 5235

get route parameters in angular with lazy loading

I would retrieve a parameter from my route path in Angular 5

http://localhost:4200/#/dashboard/74618/LastCC

I would get 74618 from route which is an id parameter.

I have processed like this

constructor(public activatedRoute: ActivatedRoute)


this.activatedRoute.paramMap.subscribe(params => {
  console.log("params******");
  params.get("id");
});

I get undefined as value.

It's working when I'm on this path http://localhost:4200/#/dashboard/74618/ (Without \LastCC )

LastCC is lazy Loaded and here's the router config:

const routes: Routes = [
  {
    path: "",
    component: CreditPointComponent
  }
];

@NgModule({
  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule]
})
export class CreditPointRoutingModule {}

The id parameter is on the parent module router configuration ( Dashboard module ).

const routes: Routes = [
  {
    path: ":id",
    component: DashboardComponent,
    children: [
      {
        path: "LastCC",
        loadChildren:
          "app/useful-documents/credit-point/credit-point.module#CreditPointModule"
      }
    ]
  }
];

Upvotes: 4

Views: 10110

Answers (1)

DeborahK
DeborahK

Reputation: 60596

You don't have a parameter configured on the LastCC route. Try something like this:

  {
    path: ":id",
    component: DashboardComponent
  },
  {
     path: ":id/LastCC",
     loadChildren:
          "app/useful-documents/credit-point/credit-point.module#CreditPointModule"
   }

Notice that the path for the LastCC route now has a route parameter: path: ":id/LastCC"

Notice also that the LastCC route is no longer a child route. Did it need to be?

If it does need to be a child route, then you may need to leave the route configuration as you have it and read the parameter from the parent's route instead of from the LastCC route.

this.activatedRoute.parent.paramMap.subscribe(params => {
  console.log("params******");
  console.log(params.get("id"));
});

Notice the .parent after the activatedRoute.

Upvotes: 5

Related Questions