Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular - How to get URL when using Hash-Strategy?

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?

like image 673
Gil Epshtain Avatar asked Sep 18 '25 13:09

Gil Epshtain


1 Answers

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

like image 95
benshabatnoam Avatar answered Sep 21 '25 04:09

benshabatnoam