-1

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?

Francesco Borzi
  • 56,083
  • 47
  • 179
  • 252
  • You can do this using `ActivatedRoute` or `Location` if you inject one of them in your constructor. Angular provides good documentation on these. – Scryper Jun 28 '23 at 11:58

2 Answers2

0
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

MGX
  • 2,534
  • 2
  • 14
  • already tried it but unfortunately `router.url` is not giving only the angular route path, but the actual full path – Francesco Borzi Jun 28 '23 at 12:43
  • [Are you sure about that ?](https://stackblitz.com/edit/stackblitz-starters-zmqksr?description=An%20angular-cli%20project%20based%20on%20@angular/animations,%20@angular/common,%20@angular/compiler,%20@angular/core,%20@angular/forms,%20@angular/platform-browser,%20@angular/platform-browser-dynamic,%20@angular/router,%20core-js,%20rxjs,%20tslib%20and%20zone.js&file=src%2Fmain.ts%3AL23&title=Angular%20Starter) – MGX Jun 28 '23 at 12:50
0

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

kemsky
  • 14,727
  • 3
  • 32
  • 51