Mubeen
Mubeen

Reputation: 431

Multiple /Dashboard routes for different Roles With AuthGuard

I want my homepage load different modules for different roles

const routes: Routes = [
      {
        path: 'login',
        component: LoginComponent,
      },
      { path: '', loadChildren: './dashboard/dashboard.module#DashboardModule', canLoad: [AuthGuard], canActivate: [AuthGuard], },
      {
        path: '',
        loadChildren: './dashboard/dashboard.module#DashboardModule',
        canActivate: [true]
      },
]

AuthGuard here

canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
  ): Observable<boolean> | Promise<boolean> | boolean {
    if (localStorage.getItem('ISTRAINER') === Role.Trainer
    && next.routeConfig.loadChildren === './dashboard/dashboard.module#DashboardModule') {
      return true;
    }
    return false;
  }
  canLoad(route: Route): boolean {
    return false;
  }

when canLoad: [AuthGuard] returns false router is not checking for next route

or is there a way to change loadChildren depending on Route

actually I want to achive that on login lets say on route "Dashboard" or on "" Student module loads if student role is logedin on route "Dashboard" or on "" Trainer module loads if Trainer role is logedin on route "Dashboard" or on "" Admin module loads if Admin role is logedin

Upvotes: 1

Views: 1787

Answers (2)

Steve
Steve

Reputation: 46

you could use the url matcher from angular https://angular.io/api/router/UrlMatcher

import { trainerMatcher } from './trainerMatcher'
import { studentMatcher } from './studentMatcher'
{
 path : '',
 matcher : trainerMatcher,
 loadChildren : 'trainerModule',
 canLoad : [AuthGuard]
},
{
 path : '',
 matcher : studentMatcher,
 loadChildren : 'studentModule'
}

Like this you can write a matcher and check there for the right role. If you still want to make sure the module can not be loaded you can set the guard after all.

I had that issue myself and found that article helpful: https://medium.com/@lenseg1/loading-different-angular-modules-or-components-on-routes-with-same-path-2bb9ba4b6566

Upvotes: 1

Andrei
Andrei

Reputation: 12036

it is expected behavior when a path is matched and angular thinks that this is the route you asked for. In your case it seems the only possible option is to update route config when the role changes. see router.resetConfig docs.

Upvotes: 0

Related Questions