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
Short and simple pure js.
location.pathname
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();
}
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)
}
}
To get current route without query parameters, you can use below mentioned single line:
this.url = this.url.substr(0, this.url.lastIndexOf("?"));
To get current route without query parameters, you can use below mentioned single line:
this.router.url.split('?')[0]
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.