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?
This is because MVC starts searching routes in RouteConfig file from top to bottom. As soon as it finds any matching route it will stop searching further. So for your problem when there will be route without param it will pick "Withoutparam" route. As I can understand from your comment below. You need url without id in every condition.
There are multiple ways to Get the URL without any parameters in JavaScript. First get the get current URL get rid of the query parameters. const url = window.location.href.split ('?') [0] Second concat origin and pathname, if there’s present a port such as example.com:80, that will be included as well.
To get current route without query parameters, you can use below mentioned single line: this.router.url.split ('?') [0] Show activity on this post. parseTree from Router helps fetching the segments without any knowledge about url structure.
window.location.pathname will give you the route path (after the base URL), in our test case /somedir/somefile Using hardcoded URLs for example.
To get current route without query parameters, you can use below mentioned single line:
this.router.url.split('?')[0]
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With