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?
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.
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.
you can subscribe to router. events and filter for NavigationEnd event to get the current active route url.
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.
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With