Angular 5: conditional module lazy loading

前端 未结 1 960
星月不相逢
星月不相逢 2021-01-20 18:33

I\'m encountering an issue while trying to lazy load module according to the user profile, I defined three default paths (with empty path for each route) and each user has a

相关标签:
1条回答
  • 2021-01-20 19:06

    The router will only try the guard on the first route that it matches. Because of this limitation you will have to try one of two options.

    The first is to implement a custom UrlMatcher that will effectively do the work of your guard and then only have it match on the module you want to load. This can be difficult if you need to make use of other services as the UrlMatcher is just a function so you won't get any DI.

    The second option is to have a generic route with path '' that has another guard on it that performs the actions of the other three guards and then routes to the appropriate module. This sounds like a bit of a hack, however, the Angular documentation suggests doing just that in the ToH tutorial.

    Demo

    Guard

    export class CanActivateModuleGuard implements CanActivate {
    
      constructor(private router: Router,
        private userGuard: CanActivateUserModuleGuard,
        private adminGuard: CanActivateAdminModuleGuard,
        private modGuard: CanActivateModeratorModuleGuard) { }
    
      canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
        let canGo = [{
          guard: this.adminGuard,
          url: 'admin',
        }, {
          guard: this.userGuard,
          url: 'user',
        }, {
          guard: this.modGuard,
          url: 'moderator',
        }].some((config) => {
          if (config.guard.canActivate(route, state)) {
            if (state.url !== `/${config.url}`) {
              this.router.navigate([config.url]);
            }
            return true;
          }
        });
    
        if (!canGo) {
          this.router.navigate(['/404']);
        }
    
        return canGo;
      }
    }
    

    Routes

    export const routes: Routes = [
      {
        path: '',
        canActivate: [CanActivateModuleGuard],
        children: [{
          path: 'user',
          loadChildren: 'app/user/user.module#UserModule',
          canActivate: [
            CanActivateUserModuleGuard
          ],
        },
        {
          path: 'admin',
          loadChildren: 'app/admin/admin.module#AdminModule',
          canActivate: [
            CanActivateAdminModuleGuard
          ]
        },
        {
          path: 'moderator',
          loadChildren: 'app/moderator/moderator.module#ModeratorModule',
          canActivate: [
            CanActivateModeratorModuleGuard
          ]
        }],
      },
      {
        path: '404',
        component: NotFoundComponent
      }
    ];
    
    0 讨论(0)
提交回复
热议问题