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?
None of these worked for me.
There are many approaches to this, but in this case a guard was in place to stop users going to specific URL's. This worked fine except when URL's had parameters as the passed URL always contained all the parameters.
E.G:
myPage/param1/param2
Or:
myPage?param1=1¶m2=2
In this case I'd want just
myPage
.I coded the below, I don't like it, I'm sure it can be improved but haven't found anything else that works so far:
state.url
comes from the implementation forCanActivate
(or injectRouter
).In my case I needed to compare the previous route and the new route, when changing only the :id on the url via router.navigate. Since I wanted the path without the different ids, I got the original path of the route:
I use locationStrategy like in accept answer but with
.split()
method. LocationStrategy work perfect in Angular 4 & Angular 5;One more things you should carry about is to be sure that your
<router-outlet>
is properly initialize before you try to getlocationStrategy.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:
But in this case you trigger your function on each router change so you need to protect this case if it's unwanted.