简体   繁体   中英

Lazy load modules conditionally on the basis of HTTP response in Angular 5

I have two roles admin and user. I have to load the admin page if userId belong to admin and user page if that userId belong to user.

The URL is something like http://example.net/[user_id] .

Is it possible that I can lazy load the modules in Angular routes on the basis of http response I get? I hit the API and pass the User Id and get the user role then I have to load the lazy load its module.

That's not possible. You can however do a redirect in a guard on the :user_id route:

export class UserRoleResolve implements CanActivate {

  constructor(private router: Router) {}

  public async canActivate(route: ActivatedRouteSnapshot): Promise<boolean> {
     const userId: string = route.params.user_id;
     const role: string = await this.getRoleFromUser(userId);

     if (role === 'admin') {
       this.router.navigateByUrl(`/admin/${userId}`);
     } else if (role === 'user') {
       this.router.navigateByUrl(`/user/${userId}`);
     }
  }
}

您可以使用以下方法解决您的问题:PreloadingStrategy。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM