javascript / intermediate
Snippet
Guarding Route Navigation with RedirectCommand on Unauthorized Access
Functional route guards can return a RedirectCommand to safely halt unauthorized navigations and redirect users to specific URL trees. Wrapping authentication checks inside try-catch blocks ensures that unexpected credential parse errors gracefully fall back to an error route rather than freezing the router.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import { inject } from '@angular/core';import { CanActivateFn, Router, RedirectCommand } from '@angular/router';import { AuthService } from './auth.service';export const authGuard: CanActivateFn = (route, state) => {const authService = inject(AuthService);const router = inject(Router);try {if (authService.isAuthenticated()) {return true;}const loginTree = router.parseUrl('/auth/login?redirect=' + encodeURIComponent(state.url));return new RedirectCommand(loginTree, { skipLocationChange: false });} catch (error) {const errorTree = router.parseUrl('/error/session-expired');return new RedirectCommand(errorTree);}};
angular
Breakdown
1
export const authGuard: CanActivateFn = (route, state) => {
Defines a functional CanActivateFn route guard taking target route snapshot and navigation state.
2
return new RedirectCommand(loginTree, { skipLocationChange: false });
Halts the current navigation cleanly and executes a redirection to the parsed login UrlTree.
3
catch (error) {
Catches unforeseen authentication evaluation errors and recovers by redirecting to a session expiration route.