Get current route without parameters

2020-06-30 04:14发布

I need to get my current route without params in Angular 2, I found a way to get the current route with params as follows:

 this.router.url

and then split it:

 this.router.url.split(';')[0]

But this looks as workaround, I think there should be better way?

9条回答
混吃等死
2楼-- · 2020-06-30 04:47

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();
}
查看更多
不美不萌又怎样
3楼-- · 2020-06-30 04:51

Native javascript will work to split the url into logical parts. Check out the "location" (or window.location) object. For example, using location at the url https://example.com/pathname1/pathname2?queryParam1=1&queryParam2=2 yields

location.origin === 'https://example.com/pathname1/pathname2'
location.href === 'https://example.com/pathname1/pathname2?queryParam1=1&queryParam2=2'
location.pathname === '/pathname1/pathname2'
location.search === '?queryParam1=1&queryParam2=2'
查看更多
虎瘦雄心在
4楼-- · 2020-06-30 04:52

this could help you:

  1. Import Router:

    import { Router } from '@angular/router';
    
  2. Signature in the constructor:

    constructor(private _router: Router) {}
    
  3. Check the _router events property:

    this._router.events
        .subscribe(
            (url:any) => {
                let _ruta = "";
                url.url.split("/").forEach(element => {
                    if(element!=="" && _ruta==="")
                        _ruta="/"+element;
                    });
                console.log("route: "+_ruta); //<<<---- Root path
                console.log("to URL:"+url.url); //<<<---- Destination URL 
                console.log("from URL:"+this._router.url);//<<<---- Current URL
            }); 
    
查看更多
Explosion°爆炸
5楼-- · 2020-06-30 04:56

To get current route without query parameters, you can use below mentioned single line:

this.router.url.split('?')[0] 
查看更多
甜甜的少女心
6楼-- · 2020-06-30 04:57

parseTree from Router helps fetching the segments without any knowledge about url structure.

import { Router } from '@angular/router';
...
constructor(private router: Router) {}
...
const urlTree = this.router.parseUrl(url);
const urlWithoutParams = urlTree.root.children['primary'].segments.map(it => it.path).join('/');

Start from here. If you have secondary outlets adjust as required.

查看更多
戒情不戒烟
7楼-- · 2020-06-30 04:57

I had a similar requirement, depending on which route I used to get the component I wanted different outcomes.

I found that activatedRoute.routeConfig.path was a great option and made it easy for me to see which route had been used.

constructor(private activatedRoute: ActivatedRoute) {}
ngOnInit() {
  if (this.route.routeConfig.path === 'heroes/:id')
查看更多
登录 后发表回答