I am using the latest angular5 version. I have the following coded routes (note that fruits and veggies are NOT parameters:
/fruits/item
/veggies/basket
Note that fruits is a parent route, and I have multiple children routes in an array (item is just one of them). 'veggies' is also a parent route. 'basket' is one of the 'child routes' in an array under the veggies route.
How can I use "ActivatedRoute", though how do I get access to the first "fruits" or "veggies" segment of the route? I want to check it and log it out to the console.
Assume Activated route is already injected into the variable "route".
Looking for something like this pseudocode(if it is correct)
showRouteRoot() {
console.log(this.route.getFirstSegmentNameInRoute())
// expected output is fruits OR veggies.
// If this can't be done in one line of code,
// multiple lines is an acceptable answer
}
I've tried:
console.log(this.route.snapshot.url.split('/'));
This yields problems.
console.log(this.route.url)
This shows me some AnonymousSubject
console.log(this.route.parent.url)
This shows me a BehaviorSubject
ActivatedRoute
provided a member pathFromRoot
which let developers to get full activedroutes from root, refer to the docs.
For your situation, you can use below code block to achieve it:
this.activatedRoute.pathFromRoot[1].url.subscribe(val => console.log(val[0].path));
Mention that currently the result of pathFromRoot
contains a empty route(first element of the ActivatedRoute[]
) which means for the path ''
.
You can do it this way :
let url = this.activatedRoute.snapshot.url.join().split(',')
console.log(url[0]);
If you want to retrieve the parent route, then have a look here.
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