I've added a canLoad guard to a state that's lazy loaded. The problem that I'm having is that I can't get any route parameters if the state is being initialized from a different state using router.navigate().
So here is my route configuration:
path: 'programs/:programId/dashboard',
loadChildren: './program.module#ProgramModule',
canLoad: [ProgramGuard]
and this is the short version of ProgramGuard:
export class ProgramGuard implements CanLoad {
canLoad(route: Route): Observable<boolean> {
//route object doesn't have any reference to the route params
let programId = paramFromRoute;
return Observable.create(observer => {
if (programId == authorizedProgramId)
observer.complete(true);
else
observer.complete(false);
}
}
}
I have tried injecting ActivatedRoute to try to get them from there to get it from there, but nothing.
If the user types the URL in the browser, then there is no problem because I can extract the parameters from the location object. But when using route.navigate, the browser's location is still set to the previous state.
Any help or ideas will be greatly appreciated.
I tried to do something similar and ended up changing to a canActivate guard instead. Note also that the canLoad guards block any preloading that you may want to do.
In theory, if a user could not access a route, it would be great to not even load it. But it practice it seems to be too limited to allow making a determination.
Something you could try (I didn't think of it earlier when I was trying to do this) ... you could add a parent route (component-less) that has a canActivate guard that can check the parameters. Then route to the lazy loaded route if the user has authorization.
I was able to retrieve the path including the route parameters using The Location
object.
canLoad() {
//dont even load the module if not logged in
if (!this.userSessionService.isSessionValid()) {
this.userSessionService.redirectUrl = this.location.path();
this.router.navigate(['/auth']);
return false;
}
return true;
}
You just need to inject the Location object in the constructor.
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