Search code examples
angularangular-router-guards

How to prevent routing and instead display a modal when navigation on a non-permission page?


In my app you can find many routerLinks everywhere across the application. Some of them may not be accessible for some users according to their roles. My auth-guard-service handles this cases.

But what in those cases happens is that the user gets navigated to the forbidden page and then back to the old page.

What I want instead of this is not navigating at all but displaying a modal or toast message (what ever) on the current site.

How can this be done? Here's some of my code:

export class AuthGuardService implements CanActivate {
  constructor(public auth: AuthServiceProvider, public router: Router, private TokenHelper: TokenHelperService) {}

  canActivate(Route: ActivatedRouteSnapshot): Observable<boolean> {
    const expectedRoles = Route.data['authenticate'] as string[];

// ...... and so on (return true or false)



Solution

  • If the forbidden page user tries to activate is in the lazy loaded module, you can prevent the navigation by putting canLoad guard.

    {
      path: 'admin',
      loadChildren: () => import('./admin/admin.module').then(mod => mod.AdminModule),
      canLoad: [AuthGuard]
    },
    

    =====

        canLoad(route: Route): boolean {
    
          return this.checkValidation();
        }
    
       checkValidation() {
       if (authService.checkRights()) { return true}
       else {
       this.toastService.showToast('Forbiden');
       return false
       }
    }
    
    }