Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2: how do I get route parameters from CanLoad implementation?

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.

like image 343
jorgenv Avatar asked May 08 '17 21:05

jorgenv


2 Answers

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.

like image 178
DeborahK Avatar answered Sep 21 '22 03:09

DeborahK


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.

like image 25
Stefan Stojkovski Avatar answered Sep 18 '22 03:09

Stefan Stojkovski