Search code examples
angulartypescriptangular-router

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?


Solution

  • 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);
    }