Angular : Get value of parameter in parent route

jophab picture jophab · Mar 29, 2019 · Viewed 14.2k times · Source

I am having URLs like

  • www.yoursite.com/accounts/:accountid/info
  • www.yoursite.com/accounts/:accountid/users etc.

An integer value accountid is available in the URL

But can't access it using the ActivatedRoute parameters.

Now I am splitting the URL to get the accountid

Is there a better way to access the value other than splitting the URL ?

Update

I have a different module called account which includes all components and services for account related pages.

I am lazy loading this module. So in the root level routing , that is app-routing I specify

{ path:'account', loadChildren : './account/account.module#AccountModule' }

In the account module's account-routing, I specify the children by

path: 'account/:accountid', component: AccountComponent, canActivate: [AuthGuard],
    children: [
      { path: '', redirectTo: 'info', pathMatch: 'full' },
      { path: 'info', component: InfoComponent },
      { path: 'users, component: UsersComponent }
      {path: '**', redirectTo: 'info'}
    ]

Note :

We can access the params in children path if present. But not of parent part why?

I am getting undefined for params in parent path

Answer

jophab picture jophab · Mar 29, 2019

With the help of this article, the problem was solved.

For accessing the params in parent route, we need to use activeRoute.parent.params instead of activeRoute.params

this.activatedRoute.parent.params.subscribe(
    (params) => 
    { 
                 console.log(params.accountid); 
     });

Also from this stackoverflow question , a solution to make all params (including parent route params) available to child routes was found.

This is done by including a configuration object with the paramsInheritanceStrategy set to always where we import RouterModule

eg :

import {RouterModule, ExtraOptions} from "@angular/router";

export const routingConfiguration: ExtraOptions = {
  paramsInheritanceStrategy: 'always'
};

export const Routing = RouterModule.forRoot(routes, routingConfiguration);

Now we can access both parent and child route params using activeRoute.params