44

When using Router ( this.router.url) I am get the string /MyRouterName?type=abc, sometime /MyRouterName if not have parameter

Can I only get the path /MyRouterName (for all cases) from the full url?

misha130
  • 5,457
  • 2
  • 29
  • 51
Phan Hoàng Nhân
  • 990
  • 1
  • 8
  • 21
  • 1
    It is hard to accept that angular is not providing a simple `pathname` property on the router state and instead we need to iterate over the url segments or use a regex to split the url. – Felix K. May 11 '18 at 17:14

11 Answers11

62

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

Akash Kumar Verma
  • 3,185
  • 2
  • 16
  • 32
user5049376
  • 1,322
  • 2
  • 14
  • 19
  • 11
    I get "TypeError: Cannot read property 'path' of undefined" for the last `console.log` statement – Bing Lu Aug 30 '16 at 16:38
  • 11
    `snapshot.url` doesnt return the states from the root on. I have this solution `this.route.snapshot.pathFromRoot.map(o => o.url[0]).join('/')` – NinjaOnSafari Feb 02 '18 at 14:44
  • 3
    This answer is not sufficient, as @NinjaOnSafari pointed out, for nested routes, one would need to iterate over the different snapshots starting from root. – Felix K. May 11 '18 at 17:37
  • 5
    Please, note, that you can use `activatedRoute` only in routable components, components within ``. In another way, use `router: Router` and call its property `router.url` to get the full URL. To get urlSegments array, call `router.parseUrl(this.router.url).root.segments`; – Mariia Bilyk Jan 13 '20 at 11:50
  • You may want full path including trailing hash and you may also not be a fan of imports. How I do it is: [answer](https://stackoverflow.com/questions/38391677/how-to-get-only-path-from-full-url-string#67186024) – Jan Ndungu Apr 20 '21 at 20:48
  • I cannot use this solution, as in mobile Safari, the activatedRoute.snapshot.url.length equals 0 (strangely, must be a browser bug?) – Hmbucker Dec 21 '21 at 08:32
16

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

Elvin Garibzade
  • 475
  • 4
  • 12
11

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);
davidvdijk
  • 121
  • 1
  • 4
  • 2
    I can also confirm that `activatedRoute.snapshot.url[0].path` throws a `TypeError: Cannot read property 'path' of undefined`. The solution that worked for me is `activatedRoute.snapshot.firstChild.url[0].path`. I am using Angular 4.0.0 and Angular CLI 1.1.0. – kimbaudi Jun 12 '17 at 17:46
7

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);
}
Nalin Adhikari
  • 586
  • 2
  • 6
  • 15
4

I have tried to use the other responses and they all end up with undefined.

So I did this:

#AppComponent
constructor(private router: Router){
  // Subscribe to RouterEvents
  this.router.events
  .subscribe((event) => {
    if (event instanceof NavigationStart) {
      // Could add more chars url:path?=;other possible
      const urlDelimitators = new RegExp(/[?//,;&:#$+=]/);
      let currentUrlPath = event.url.slice(1).split(urlDelimitators)[0];
      console.log('URL_PATH: ', currentUrlPath);
    }
  });
}

I subscribe to the router changes so when NavitionStartEvent happens a new URL_PATH is found.

T04435
  • 12,507
  • 5
  • 54
  • 54
3

Isn't this simple and effective?

let path = this.router.url.split("?")[0];
Playdome.io
  • 3,137
  • 2
  • 17
  • 34
2

For me, this is the cleanest solution I managed to do. I hope it helps

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

constructor(private router: Router){}

getUrlWithoutParams(){
   let urlTree = this.router.parseUrl(this.router.url);
   urlTree.queryParams = {}; 
   return urlTree.toString();
}
2

Following approach worked for me in Angular 8

URL

http://localhost:4200/admin/audit_trail

What I wanted to extract?

admin

Code

constructor(
    private route: ActivatedRoute
) {
    const path = this.route.snapshot.parent.routeConfig.path;
}

// path = 'admin'
Pradeep Vig
  • 485
  • 6
  • 7
0

If you don't need to support IE you can use the URL class to do reverse-engineer the url components from the string:

(new URL(this.router.url), 'x:/').pathName

Considering your example, the code above would yield only the "/MyRouterName" part of "/MyRouterName?type=abc".

Note: the 'x:/' part only exists to satisfy the URL class' need for a protocoll (which this.router.url doesn't provide).

Felix K.
  • 14,171
  • 9
  • 58
  • 72
0

Below code works with both: non-hash and hash (e.g https://site/#/user)urls

public openInNewTab(router: Router, namedRoute ) {
      let newRelativeUrl = router.createUrlTree([namedRoute]);
      let baseUrl = window.location.href.replace(router.url,'');

      window.open(baseUrl + newRelativeUrl, '_blank');
}
Kamil Kiełczewski
  • 85,173
  • 29
  • 368
  • 345
0

Great answers here... Allow me to add an alternative:

The UrlReflectionService provided by the @bespunky/angular-zen library.

import { Component            } from '@angular/core';
import { UrlReflectionService } from '@bespunky/angular-zen/router-x';

@Component({
    selector   : 'app-demo',
    templateUrl: './demo.component.html',
    styleUrls  : ['./demo.component.css']
})
export class DemoComponent
{   
    constructor(public urlReflection: UrlReflectionService)
    {
        // use properties (e.g. `routeUrl`, `queryString`) from `this.urlReflection`
        // to extract parts of the current url

        // use methods (e.g. `routeOf()`, `queryStringOf()`) from `this.urlReflection`
        // to extract parts of any url 
    }
}

Live Example

TLDR 1

The service facilitates all kinds of url extraction and manipulation operation, and even exposes the RegEx objects it internally uses in case you need further customization.

TLDR 2

Remember to:

  1. npm install @bespunky/angular-zen

  2. Import RouterXModule (for root or child).

Shy Agam
  • 1,285
  • 1
  • 13
  • 37