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> { ... }