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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With