Angular - Get Route Parameters from parent route

1.7k Views Asked by At

I have a global routing module which allows me to correctly navigate to my component module which is lazy loaded.

Inside the component module I have a child route which can be correctly loaded. What I can't seem to do however is access the userID parameter from inside the albums path (the child of the userDetailComponent)

I've tried the following, but it returns as undefined.

this.activatedRoute.params.subscribe((urlParameters) => {
  this.user_id = urlParameters['userID'];
}

Below is my routing configuration. Any help would be greatly appreciated.

app-routing.module.ts

const routes: Routes = [
  { 
     path: 'users', 
     loadChildren: '../app/users/users.module#UsersModule' 
  },
  {
     path: 'users/:userID',
     loadChildren: '../app/component/component.module#ComponentModule' 
   }
]

component.module.ts

const routes: Routes = [
  {
    path: '',
    component: UserDetailComponent,
    children: [
      {
        path: 'albums',
        loadChildren: '../app/albums/albums.module#AlbumsModule';
      },
    ]
  },
]
1

There are 1 best solutions below

1
On

albums path is child of UserDetailComponent's route, and UserDetailComponent's route is child of users/:userId. So when you are inside albums route, you should get params of UserDetailComponent's route by routing tree. You can access parent of your route using ActivatedRoute.parent (it returns route which is parent of your current route)