The easiest and most efficient way to get the current route URL in Angular is to subscribe to the router events and then use the url
property of these events to get the current URL.
To do this, you have to first inject the Router’s dependency into the class constructor and then you can subscribe to its router events.
Once subscribed, you have to check if the navigation has ended successfully or not by checking if the router event is an instance of the NavigationEnd
:
import { Component, OnDestroy, OnInit } from '@angular/core'; import { NavigationEnd, Router } from '@angular/router'; export class ProductsComponent implements OnInit, OnDestroy { routerEvents: any; constructor(private router: Router) { this.routerEvents = this.router.events.subscribe( (event:any)=>{ if(event instanceof NavigationEnd){ console.log(event.url); // Prints the current route // Eg.- /products } } ) } ngOnInit(): void { } ngOnDestroy(): void { this.routerEvents.unsubscribe(); // Unsubscribe to avoid memory leak } }
Note: Do not forget to unsubscribe from the router events when the component is destroyed. Because, if you do not unsubscribe, the subscription keeps on running and it prints every route you visit. This can ultimately lead to the memory leak problem.
Using Router.url to get the Current Route URL
An alternative approach could be to use the Router.url
property to get the current route url.
This is how you can add to your ts file:
import { Router } from '@angular/router'; constructor(private router: Router) { console.log(this.router.url); // Prints the current route URL // Eg. - /products }
Using Location Service to get the Current Route URL
You can also get the current route URL by calling the Location.path()
method. The Location
service can be imported from the @angular/common
library.
Once imported, you can inject it into the class constructor and directly call the path()
method on it to get the current route URL:
import { Location } from '@angular/common'; constructor(private location: Location) { console.log(this.location.path()); // Prints current route URL // Eg- /products }