Skip to content
Angular Essentials
GitHub

Guards

Available guards: https://angular.io/api/router#structures

The class-based implementation of guards has been @deprecated. Functional router guards replace the class-based approach.

// auth.constants.ts
export const authGuard = () => {
    const authService = inject(AuthService);
    const router = inject(Router);
    console.log('AuthGuard called');
    return authService.isAuthenticated() ? true : router.navigate(['']);
};
// app.routes.ts
export const routes: Routes = [
  {path: '', redirectTo: 'sports', pathMatch: 'full'},
  {path: 'sports', loadChildren: () => import('./forms/sports/sports.routes').then(m => m.routes)},
  {
    path: 'grocery',
    canActivate: [authGuard],
    loadChildren: () => import('./forms/grocery/grocery.routes').then(m => m.routes)
  }
];
  • canActivate decides if a route can be accessed. If all guards return true, navigation continues. If any guard returns false, navigation is cancelled. If any guard returns a UrlTree, the current navigation is cancelled and a new navigation begins to the UrlTree returned from the guard.
  • ActivatedRouteSnapshot contains the information about a route associated with a component loaded in an outlet at a particular moment in time.
  • RouterStateSnapshot represents the state of the router at a moment in time.
  • Here, we simply inject AuthService and Router in authGuard.
  • And we return true if user is loggedIn, else we navigate user to blank page.

canActivate and other guards accept array which means we can provide multiple guards to single route.