I'm using { provide: LocationStrategy, useClass: HashLocationStrategy },
in my app.module.ts
. But when I give this.route.url
it always contains /
whether I'm in /home
or /dashboard
or /profile
I need to get the particular route value
constructor(public router:Router) {} alert(this.router.url);
you can subscribe to router. events and filter for NavigationEnd event to get the current active route url.
Step 1: Inject Router Firstly, we have to inject Router in the component which will listen for events. Step 2: Subscribe on events Then, we subscribe to Router events. Step 3: Handle type of event Router events stream fires all router events.
NavigationEndlinkAn event triggered when a navigation ends successfully. class NavigationEnd extends RouterEvent { constructor(id: number, url: string, urlAfterRedirects: string) type: EventType.
Not sure if this applies to v5, but may help anyway
You can also subscribe to router event NavigationEnd, this seems to be the best way to always get the current url.
important notes:
- make sure you place this code in the contructor()
of the app.component.ts
file, in order to always get the last url value.
// file: src/app/app-component
export class AppComponent {
constructor(private router: Router) {
// listen to events from Router
this.router.events.subscribe(event => {
if(event instanceof NavigationEnd) {
// event is an instance of NavigationEnd, get url!
const url = event.urlAfterRedirects;
console.log('url is', url);
}
})
}
}
Your route
instance should be from Router
constructor(
private router: Router
) { }
this.router.url // this must contains your full router path
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