1

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

emkay
  • 777
  • 8
  • 19
Mubeen
  • 351
  • 1
  • 2
  • 15
  • you can route to your path from typescript based on the condition inside the canActivate function. – emkay Mar 05 '19 at 07:17
  • added some more explanation kindly review that too – Mubeen Mar 05 '19 at 07:23
  • So you will be having 3 **dashboard components** in the **dashboard module**? Like for student you have a student dashboard, admin -> admin dashboard, teacher -> teacher dashboard. And for whatever will be in localStorage, you will route to that particular dashboard? Is this the usecase? – emkay Mar 05 '19 at 07:28

2 Answers2

1

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

Steve
  • 46
  • 4
0

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.

Andrei
  • 10,117
  • 13
  • 21