javascript / intermediate
Snippet
Route Protection with CanMatch
CanMatch guards determine if a route should even be considered for matching, allowing for cleaner routing logic compared to traditional CanActivate guards.
snippet.js
javascript
1
2
3
4
5
6
export const adminMatchGuard: CanMatchFn = (route, segments) => {const isAdmin = inject(AuthService).isAdmin();return isAdmin || new RedirectCommand(router.parseUrl('/unauthorized'));};{ path: 'dashboard', canMatch: [adminMatchGuard], component: AdminComponent }
angular
Breakdown
1
CanMatchFn
A functional type for guards that control route selection.
2
RedirectCommand
A modern way to return a navigation command directly from a guard.
3
canMatch: [adminMatchGuard]
Specifies the guard used to decide if the route matches the URL.