Search code examples
angularangular-routingangular-router

Angular Router ActivatedRoute


I want to check the address bar if it contains "admin" or not

Address: http://localhost:4200/admin

constructor(
private route: ActivatedRoute
 ){
  this.route.paramMap.subscribe((paramMap: ParamMap) =>{
  console.log(paramMap.has('/admin'));
  }
)

but it gives me false. I expected true


Solution

  • If you want to do this in constructor, use Location service instead of router:

    import { Location } from '@angular/common';
    
    constructor(private location: Location){
      if (this.location.path().startsWith('/admin')) {
        console.log('true');
      }
    }
    

    Router.url is initialised with / (and populated with real url later), while Location.path() will return the real url right away.