Route guards are functions (or classes in older Angular) that the router runs to decide whether navigation may continue. They return true, false, a UrlTree (redirect), or an Observable or Promise of those values. Main guard types - canActivate: can the user enter this route? (for example, logged in) - canActivateChild: same check for all child routes. - canMatch: should this route definition even match? Useful to choose between routes or to avoid downloading a lazy module the user cannot use. (Replaced the deprecated canLoad.) - canDeactivate: can the user leave? Typically used to warn about unsaved changes. - resolve (a resolver, closely related): fetch data before the route activates. Functional guard example (Angular 15+): export const authGuard: CanActivateFn = (route, state) => { const auth = inject(AuthService); const router = inject(Router); return auth.isLoggedIn() ? true : router.createUrlTree(['/login'], { queryParams: { returnUrl: state.url } }); }; export const roleGuard = (role: string): CanActivateFn => () => inject(AuthService).hasRole(role) || inject(Router).createUrlTree(['/forbidden']); Using them: { path: 'admin', canMatch: [roleGuard('Admin')], loadChildren: () => import('./admin/routes') }, { path: 'profile', canActivate: [authGuard], component: ProfileComponent }, { path: 'edit/:id', canDeactivate: [unsavedChangesGuard], component: EditComponent } Unsaved changes guard: export const unsavedChangesGuard: CanDeactivateFn<EditComponent> = component => !component.form.dirty || confirm('Discard unsaved changes?'); Important point for interviews: guards only control navigation in the browser and can be bypassed. They improve user experience; real security must be enforced by the backend on every API request.
Ravindra Wadile · · 0 likes