Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get all route params/data

Given a route config

{    path: '/root/:rootId',    children: [{        path: '/child1/:child1Id',        children: [{            path: '/child2/:child2Id            component: TestComponent        }]    }] } 

In TestComponent how can I easily get all route params. I'm wondering if there is an easier way than

let rootId = route.parent.parent.snapshot.params; let child1Id = route.parent.snapshot.params; let child2Id = route.snapshot.params; 

This seems overly redundant especially if I'm watching the route params observable instead of access the param through the route snapshot. This method also seems fragile since it would break If I moved any any of the routes/params around. Im used to angular ui-router where a single object $stateParams was supplied with all param data easily accessible. I have these same concerns with route resolved data along being accessed from a single node in the route tree. Any help would be much appreciated. Thanks in advance

like image 535
user2370392 Avatar asked Feb 17 '17 14:02

user2370392


People also ask

How will you extract route parameters?

To extract the parameter, you need to make the dynamic parameter in the route path so that you can extract the value of the parameter by parameter name.

Which service can be used to extract route parameters inside component?

Custom pipe can modify actual value of variable apart from different presention in HTML.

What is the difference between ActivatedRoute and ActivatedRouteSnapshot?

Since ActivatedRoute can be reused, ActivatedRouteSnapshot is an immutable object representing a particular version of ActivatedRoute . It exposes all the same properties as ActivatedRoute as plain values, while ActivatedRoute exposes them as observables.


1 Answers

As of Angular 5.2, you can do Router configuration to inherit all params to child states. See this commit if interested in the gory details, but here's how it's working for me:

Wherever you have your call to RouterModule.forRoot(), include a configuration object with the inheritance strategy set to always (default is emptyOnly):

import {RouterModule, ExtraOptions} from "@angular/router";  export const routingConfiguration: ExtraOptions = {   paramsInheritanceStrategy: 'always' };  export const Routing = RouterModule.forRoot(routes, routingConfiguration); 

Now when you're in a child component looking at a ActivatedRoute, ancestors' params appear there (e.g. activatedRoute.params) rather than something messy like activatedRoute.parent.parent.parent.params. You could access the value directly (e.g. activatedRoute.params.value.userId) or subscribe via activatedRoute.params.subscribe(...).

like image 181
jmq Avatar answered Sep 28 '22 09:09

jmq