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
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
Try this solution:
this.activatedRoute.params.subscribe(params => {
const accountid= params['accountid'];
});
You can also try this if above didn't work. (Got this solution from here)
this.router.parent.params.switchMap(params => {
// params = { id: 1234 }
});
All you need is to use paramsInheritanceStrategy
. See https://angular.io/api/router/ExtraOptions
The parent
property has been added to the route now:
this.route.parent.paramMap
.subscribe(params => {
if (params.has('accountid')) {
this.'accountid'= params.get('accountid');
}
});
Try this
create the object of ActivatedRoute in constructor
constructor(private route: ActivatedRoute) {}
so once object get created you will get route parameters like
let accountid = this.route.snapshot.params['accountid'];
console.log(accountid);
OR
let accountid = this.activatedRoute.snapshot.paramMap.get('accountid');
console.log(accountid);
I hope this will be useful.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With