Home > Enterprise >  How to pass data to route with lazy loaded module?
How to pass data to route with lazy loaded module?

Time:03-17

I am using Angular 12 and I have route path with lazy laoded module like this. I have no clue why passing roles in data object like this is not working. Wehn I am trying to read data in my AuthGuard, data object is empty. I would be grateful for any tips.

route path

      {
        path: RoutePath.Users,
        loadChildren: () => import('../users/users.module').then(m => m.UsersModule),
        canActivate: [AuthGuard],
        data: {roles: [UserRole.Admin, UserRole.SuperAdmin]}
      },

auth.guard.ts

    constructor(private store: Store, private router: Router, private activatedRoute: ActivatedRoute) {
  }

  public canActivate(): Observable<boolean> {
    console.log(this.activatedRoute.snapshot.data);
  }

CodePudding user response:

 {
    path: RoutePath.Users,
    loadChildren: () => import('../users/users.module').then(m => m.UsersModule),
    canActivate: [AuthGuard],
    data: {roles: [UserRole.Admin, UserRole.SuperAdmin]}
  },

// Here I'm adding the CANACIIVATE function sample, you can access the data from ActivatedRouteSnapshot instance, here it is NEXT

canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
    console.log(next.data); // you can access the data from ActivatedRouteSnapshot instance, here it is NEXT
    return false;
}
  • Related