How to get only path from full url string

This works for me.

Import this :

import { Router } from '@angular/router';

then pass it to the constructor :

path: any;

constructor(private router: Router) {
  this.path = this.router.url;
  console.log(this.path);
}

if you reload page , you can not get route path by Router or ActivatedRoute . You can use window.location.pathname instead of that.


The answer user5049376 has given didn't work for me. the url property was undefined.

console.log(activatedRoute.snapshot.url[0].path); 

instead of that I used the firstChild property.

console.log(this.activatedRoute.snapshot.firstChild.url[0].path);

You can use the activated route component's snapshot to get this url.

    import { Router, ActivatedRoute } from '@angular/router';
     constructor(
        private router: Router,
        private activatedRoute: ActivatedRoute) {

        console.log("routes");
        console.log(activatedRoute.snapshot.url); // array of states
        console.log(activatedRoute.snapshot.url[0].path); 
    }

Link to original SO answer by Jose G Varanam How to get current route