typescript
49 lines · 5 steps
Functional route guards in Angular
Two CanActivateFn guards gate routes on auth state and user roles, redirecting via UrlTree when access is denied.
Explained by
highlit
1import { inject } from '@angular/core';
2import {
3 CanActivateFn,
4 Router,
5 ActivatedRouteSnapshot,
6 RouterStateSnapshot,
7} from '@angular/router';
8import { map, take } from 'rxjs/operators';
9
10import { AuthService } from '../services/auth.service';
11
12export const authGuard: CanActivateFn = (
13 route: ActivatedRouteSnapshot,
14 state: RouterStateSnapshot,
15) => {
16 const auth = inject(AuthService);
17 const router = inject(Router);
18
19 return auth.isAuthenticated$.pipe(
20 take(1),
21 map((isAuthenticated) => {
22 if (isAuthenticated) {
23 return true;
24 }
25
26 return router.createUrlTree(['/login'], {
27 queryParams: { returnUrl: state.url },
28 });
29 }),
30 );
31};
32
33export const roleGuard = (...allowedRoles: string[]): CanActivateFn => {
34 return () => {
35 const auth = inject(AuthService);
36 const router = inject(Router);
37
38 return auth.currentUser$.pipe(
39 take(1),
40 map((user) => {
41 if (user && allowedRoles.includes(user.role)) {
42 return true;
43 }
44
45 return router.createUrlTree(['/forbidden']);
46 }),
47 );
48 };
49};
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Functional guards use inject() to grab dependencies without a class or constructor.
- 2Returning a UrlTree from a guard performs a redirect instead of a plain block.
- 3Wrapping a guard in a factory lets you parameterize it, like passing allowed roles.
Related explainers
typescript
import { Component } from '@angular/core'; import { RouterLink, RouterLinkActive } from '@angular/router'; import { NgFor } from '@angular/common';
Building an active-route navbar in Angular
routing
standalone-components
accessibility
Intermediate
6 steps
go
package middleware import ( "net/http"
Role-based access control middleware in Gin
middleware
authorization
closures
Intermediate
7 steps
java
@Component public class RefreshTokenSuccessHandler implements AuthenticationSuccessHandler { private final RefreshTokenService refreshTokenService;
Issuing JWT and refresh tokens on login in Spring
authentication
jwt
http-cookies
Intermediate
7 steps
typescript
type Masker = (value: string) => string; const maskEmail: Masker = (value) => { const [local, domain] = value.split("@");
Recursively masking sensitive data for logs
recursion
regex
data-masking
Intermediate
9 steps
java
import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.databind.JsonSerializer; import com.fasterxml.jackson.databind.SerializerProvider; import com.fasterxml.jackson.databind.module.SimpleModule;
Serializing Money to JSON in Spring
serialization
jackson
money
Intermediate
8 steps
typescript
interface ParsedName { first: string; middle: string; last: string;
Parsing human names into structured parts
parsing
string-manipulation
normalization
Intermediate
9 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/functional-route-guards-in-angular-explained-typescript-f0f7/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.