Angular router: get the full URL of a given route

1.6k views Asked by At

Given that my Angular apps runs in https://www.somewebsite.com/some-path/my-app/

And I have some routes for example:

https://www.somewebsite.com/some-path/my-app/my-route-1

https://www.somewebsite.com/some-path/my-app/my-route-2

Inside the application, given a specific route, for example my-route-1, is there a method of the angular Router or similar that would return the full URL https://www.somewebsite.com/some-path/my-app/my-route-1 ?

For example in my case such a method:

this.router.getUrlOfRoute('my-route-1')

would return https://www.somewebsite.com/some-path/my-app/my-route-1.

In other words, what navigate() typically does with:

this.router.navigate(['/my-route-1'])

in my example would be redirecting the user to https://www.somewebsite.com/some-path/my-app/my-route-1.

What if I just want to get the URL as a string instead of triggering the actual navigation?

2

There are 2 answers

2
MGX On
constructor(private router: Router) {
  console.lgo(router.url);
}

This will give you the router URL, simply add the location.origin before it and you should be good

Also, you can simply use location.href to get it full, but I imagine you don't want that

0
kemsky On

You can try to use Router's createUrlTree method and then pass result to serializeUrl.