9

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

Rolando
  • 58,640
  • 98
  • 266
  • 407

3 Answers3

13

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

Zoe
  • 27,060
  • 21
  • 118
  • 148
Pengyy
  • 37,383
  • 15
  • 83
  • 73
10

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.

Amit Chigadani
  • 28,482
  • 13
  • 80
  • 98
  • am getting split is not a property of this.activatedRoute.snapshot.url – Rolando Apr 06 '18 at 03:28
  • it still says property "split" does not exist on urlsegment. This is angular 5. – Rolando Apr 06 '18 at 03:41
  • So it only says "item" or "basket". It does not say "fruits" or "veggies". The way I have the routes defined, is there is a parent route (fruits or veggies), and I have an array of "children" routes under that. – Rolando Apr 06 '18 at 03:45
  • Look at the url in my answer to retrieve parent route. That should help you. – Amit Chigadani Apr 06 '18 at 03:54
0

We can use Router like...

this.router.routerState.snapshot.url.split('/').at(-1)

No need of ActivatedRoute.

Vikram Sapate
  • 1,087
  • 1
  • 11
  • 16