4

In my Angular Route, I define that I'm using Hash strategy:

// app-routing-module.ts
@NgModule({
  imports: [
    RouterModule.forRoot(routes, {
      useHash: true
    })
  ],
//...

When I want to test the current Router url, I run this code:

import { Router } from '@angular/router';
// ..

constructor(private _router: Router) {}

getUrl() {
  return this._router.url; // always return '/'
}

The this._router.url is always equal to '/'. However, if I test window.location.href, I'm getting a different value (the real full url).

How do I get the current router-url (in the Angular way, not via window object) while using Hash Strategy?

2
  • Why router? Why not route snapshot? Not different angular api using with and without hash strategy. Commented Dec 29, 2019 at 18:11
  • @Numichi - could you post an Answer where you explain how to get the router url with snapshot route Commented Dec 30, 2019 at 8:19

2 Answers 2

2

You can use PlatformLocation class like this:

import { PlatformLocation } from '@angular/common';

constructor(private pLocation: PlatformLocation) { }

getUrl() {
  return (pLocation as any).location.href;
}

The reason I coded (pLocation as any) is that location is not showing it typescript intellisense, as you can see it is not showing in Angular docs, but it is there and you can use it.

SIMPLE DEMO

Sign up to request clarification or add additional context in comments.

1 Comment

Great. What I was needed was actually platformLocation.hash which was equal to #/page1 (the part after the '#' of the url)
2

You should use ActivatedRoute to get URL as Numichi mentioned

1 Comment

Could you add an example of use. How do I get the URL from ActivatedRoute

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.