Get current route without parameters

前端 未结 12 1243
梦如初夏
梦如初夏 2021-01-01 09:08

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

相关标签:
12条回答
  • 2021-01-01 09:22

    Short and simple pure js.

    location.pathname
    
    0 讨论(0)
  • 2021-01-01 09:33

    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 讨论(0)
  • 2021-01-01 09:34

    If you are using webpack, you can use the url polyfill module which comes bundled, along with the Angular Router module.

    import { Component, OnInit } from '@angular/core';
    import { Router } from '@angular/router';
    import * as url from 'url'
    
    @Component({
      selector: 'app-component',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.scss']
    })
    export class AppComponent implements OnInit {
    
      public constructor(public readonly router: Router) {}
    
      public ngOnInit() {
        const urlInfo = url.parse(this.router.url)
        console.log(urlInfo.pathname)
      }
    }
    
    0 讨论(0)
  • 2021-01-01 09:36

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

    this.url = this.url.substr(0, this.url.lastIndexOf("?"));
    
    0 讨论(0)
  • 2021-01-01 09:37

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

    this.router.url.split('?')[0] 
    
    0 讨论(0)
  • 2021-01-01 09:37

    I use locationStrategy like in accept answer but with .split() method. LocationStrategy work perfect in Angular 4 & Angular 5;

    import {LocationStrategy} from '@angular/common';
    
    export class MyService {
        constructor(private locationStrategy: LocationStrategy) {
        }
    
        public getUrl(filters: FilterConfig[]): void {
            const url = this.locationStrategy.path();
            const urlArray = url.split('?');
    
            return urlArray[0];
        }
    }
    

    One more things you should carry about is to be sure that your <router-outlet> is properly initialize before you try to get locationStrategy.path(). If <router-outlet> isn't initialize any Angular services can't return URL and query params properly.

    To be sure that you location strategy is initialize you can use subscribe method like:

    this.router.events.subscribe((evt) => {
    ...
    }
    

    But in this case you trigger your function on each router change so you need to protect this case if it's unwanted.

    0 讨论(0)
提交回复
热议问题