35

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?

Phan Hoàng Nhân
  • 900
  • 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

51

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
  • 2,954
  • 2
  • 14
  • 27
user5049376
  • 1,202
  • 2
  • 14
  • 19
  • 10
    I get "TypeError: Cannot read property 'path' of undefined" for the last `console.log` statement – Bing Lu Aug 30 '16 at 16:38
  • 9
    `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
  • 2
    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
  • 3
    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
13

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
  • 445
  • 4
  • 12
9

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
  • 101
  • 1
  • 3
  • 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
6

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
  • 556
  • 2
  • 8
  • 15
3

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
  • 10,027
  • 3
  • 49
  • 51
3

Isn't this simple and effective?

let path = this.router.url.split("?")[0];
Playdome.io
  • 2,833
  • 2
  • 14
  • 29
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();
}
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.
  • 11,650
  • 8
  • 53
  • 63
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
  • 71,169
  • 26
  • 324
  • 295
0

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
  • 365
  • 2
  • 7
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,125
  • 1
  • 11
  • 34