Home > Net >  Angular router get relative url path
Angular router get relative url path

Time:11-08

My angular app is hosted on prod server on this url:

myserver/myapp

However on localhost its on default

localhost:4200

The landing page is

"/mainpage" //(myserver/myapp/mainpage, or localhost:4200/mainpage)

I need to get the current page url (to save it as query parameter and redirect back after relogin on background), but I need only that one, that is configured in app-routing.module (/mainpage), and not the whole url. I tried

window.location.pathname

or

router.routerState.snapshot.url

but both are returing different values on dev or prod. on dev its correctly: mainpage but on prod, its: myapp/mainpage, and thus the redirection is wrong:

myserver/myapp/myapp/mainpage

It should be independend from the host server url:

/mainpage

CodePudding user response:

If you know that basepath myserver/myapp is part of the server, then why not just remove that part of the string, something like:

let url = router.routerState.snapshot.url

url.replace('myserver/myapp', '')

Above is the fastest fix if your server path doesn't change often.

But if you need more dynamic solution, you have to look into setting APP_BASE_HREF or using HashLocationStrategy.

The benefit of using HashLocationStrategy is then window.location.hash will return you the path starting from #, i.e. "something.com/myserver/myapp/#/mainpage" will return "#/mainpage"

CodePudding user response:

So the solution is simple, but mine dev environment was in wierd state, therefore the issue was still there, even if the new code seems to be deployed. So I thought, this solution does not works.

For getting only routing url without base url, use:

router.routerState.snapshot.url

For setting it as query params:

router.navigate(['/navigateToAndAppendQueryParams'], { queryParams: { myRedirectUrl: router.routerState.snapshot.url } });

Optionally for reading the query params:

router.navigate([(router.getCurrentNavigation()?.extractedUrl.queryParams as any).redirectUrl]);
  • Related