Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get angular 5 route segments from ActivatedRoute?

Tags:

angular

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

like image 842
Rolando Avatar asked Apr 06 '18 02:04

Rolando


2 Answers

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 ''.

like image 191
Pengyy Avatar answered Oct 11 '22 23:10

Pengyy


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.

like image 31
Amit Chigadani Avatar answered Oct 11 '22 22:10

Amit Chigadani