1

Do you know that if you want to go to another page you can use the following code?

this.router.navigate(['section1', 'section1-children', 'my-page']);

Here, as you know, every string in the array is a path declared in the routing file of the module that loads the related component.

Now, if the component in which I want to use the navigate method is agnostic about routing paths, how to retrieve the array of strings corresponding to the full current path?

I would like to have code like the following:

let path:Array<string> = this.router.getCurrentArray();
path.push('my-page');
this.router.navigate(path);

I have tried to use ActivatedRoute service, but the only useful method I found is the following:

this.activatedRoute.pathFromRoot;

that returns an array of Route, not strings.

Do you know a better way to reach my purpose?

smartmouse
  • 13,912
  • 34
  • 100
  • 166

2 Answers2

3

You can use

this.router.navigate('../' + path);

with one of the entries from

path = this.router.config[x].path;

You should be able to get the full path by

this.router.routerState.snapshot.url

This only works with Router instances injected into the component added by the router for this route.

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • The `config` is not what I was looking for. The second way force me to use `navigateByUrl` method instead of `navigate`. Am I right? – smartmouse Feb 23 '17 at 13:48
  • 1
    Just saw `this.activatedRoute.pathFromRoot;` provides all segments at once, that's better than iterating yourself. `config` is meant to get the available (child) routes, I misinterpreted your question a bit. What if you concatenate the `path` segments from `pathFromRoot` entries? https://angular.io/docs/ts/latest/api/router/index/UrlSegment-class.html#!#path-anchor – Günter Zöchbauer Feb 23 '17 at 13:53
  • Both ways, yours or mine, in my opinion are "dirty" ways of get the current path. It is weird that there isn't a better way. – smartmouse Feb 23 '17 at 14:13
  • 1
    Yup, you're not the first who asks ;-) – Günter Zöchbauer Feb 23 '17 at 14:14
0

Summarized from @Günter Zöchbauer comment:

constructor(private router: Router) {
    let tree: UrlTree = this.router.parseUrl(this.router.routerState.snapshot.url);
    let g: UrlSegmentGroup = tree.root.children[PRIMARY_OUTLET];
    let s: UrlSegment[] = g.segments;
    return s.map(a => a.path);
}
Felix
  • 3,999
  • 3
  • 42
  • 66