Search code examples
angularroutesangular2-routingangular2-router3navigatetourl

Angular2: how to retrieve path array from Router?


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?


Solution

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