0 day streak
javascript / expert
Snippet

Functional Permission Guards with Redirect Logic

Modern Angular applications use functional guards instead of class-based ones. This snippet demonstrates how to leverage 'inject' to access services within a function and return a 'UrlTree' for seamless redirection when permissions are missing.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
import { inject } from '@angular/core';
import { CanActivateFn, Router } from '@angular/router';
import { AuthService } from './auth.service';
export const roleGuard: CanActivateFn = (route) => {
const authService = inject(AuthService);
const router = inject(Router);
const expectedRole = route.data['role'];
return authService.hasRole(expectedRole)
|| router.createUrlTree(['/unauthorized']);
};
angular
Breakdown
1
CanActivateFn
The functional interface type for modern Angular route guards.
2
inject(AuthService)
Uses functional Dependency Injection to retrieve instances without a constructor.
3
router.createUrlTree(...)
Returns a navigation instruction that Angular's router uses to redirect the user if the guard fails.