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:
let url: string = state.url;
let urlParams: string[];
if (url.includes("?")) {
url = url.substr(0, url.indexOf('?'));
} else {
urlParams = route.url.toString().split(';')[0].split(',');
if (urlParams.length > 1) {
urlParams.shift(); // Remove first element which is page name
// Get entire splitting on each param
let fullUrlSegments: string[] = state.url.split('/');
// Remove number of params from full URL
fullUrlSegments = fullUrlSegments.slice(0, fullUrlSegments.length - urlParams.length);
url = fullUrlSegments.join('/');
}
}
alert(url);
state.url
comes from the implementation for CanActivate
(or inject Router
).
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) Observable<boolean> { ... }
this.dom.URL.split('?')[0]
-> where dom is instance ofDOCUMENT
@angular/router
and then "simply" usethis.router.parseUrl(this.router.url).root.children.primary.segments
. If the goal was to make as many developers as possible prefer Vue or React over Angular, it's a job very well done. Hat off, Angular architects! And no, providing subscriptions is not enough. What if I want to get the activated route params in a component created after route has changed (i.e: a modal)? You need to expose subscriptions as well as methods to get the current value. Make it easy to use for children! That's your goal!