Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get URL that would be generated by router.navigate

I'm wondering if there's a way to get the URL that would be generated by Angular's router when calling the navigate method.

For example:

this._router.navigate(['browse'], { queryParams: { section: 'users', isActive: true } });

might result in a navigation to /browse#?section=users&isActive=true

How can I get this route without performing the navigation or updating the URL in the browser?

like image 350
garethdn Avatar asked Dec 13 '17 14:12

garethdn


People also ask

How do I find my current route URL?

Steps to get current route URL in Angular. Import Router,NavigationEnd from '@angular/router' and inject in the constructor. Subscribe to the NavigationEnd event of the router. Get the current route url by accessing NavigationEnd's url property.

What is router navigate?

In Angular, RouterLink is a directive for navigating to a different route declaratively. Router. navigate and Router. navigateByURL are two methods available to the Router class to navigate imperatively in your component classes.

How do I get current URL in app component?

you can subscribe to router. events and filter for NavigationEnd event to get the current active route url.

What is the difference between navigate and navigateByUrl?

It has two methods, navigate and navigateByUrl , that navigate the routes. They are similar; the only difference is that the navigate method takes an array that joins together and works as the URL, and the navigateByUrl method takes an absolute path.


1 Answers

Have a look at createUrlTree:

this._router.createUrlTree(
    ['browse'], { queryParams: { section: 'users', isActive: true } });

The returned object, a UrlTree has a toString function that should give you what you want.

You can see from the source that navigate actually uses createUrlTree internally:

navigate(commands: any[], extras: NavigationExtras = {skipLocationChange: false}):
        Promise<boolean> {
    validateCommands(commands);
    return this.navigateByUrl(this.createUrlTree(commands, extras), extras);
}
like image 71
Kirk Larkin Avatar answered Oct 08 '22 00:10

Kirk Larkin