CHAPTER 22
Beginner
Angular Guards and Interceptors
Updated: May 18, 2026
5 min read
# CHAPTER 22
Angular Guards and Interceptors
1. Chapter Introduction
Two of Angular's most powerful features for production applications are Guards and Interceptors. Route Guards prevent unauthorized users from accessing protected pages. HTTP Interceptors automatically modify outgoing HTTP requests (like adding an auth token) and incoming responses (like handling 401 errors globally) — without writing that code in every single service.2. Learning Objectives
-
Create a
CanActivateguard to protect routes.
- Implement role-based guards.
- Create an HTTP Interceptor for automatic token injection.
- Handle global HTTP error responses (401, 500).
3. Route Guard — CanActivate
bash
auth.guard.ts
app.routes.ts
4. Role-Based Guard
role.guard.ts
5. Functional Guards (Modern Angular)
Modern Angular (v15+) supports guard functions instead of classes:
auth.guard.ts
typescript
6. HTTP Interceptor — Auto Token Injection
bash
auth.interceptor.ts
7. Global Error Handling Interceptor
typescript
8. Registering Interceptors
app.config.ts
9. Common Mistakes
-
Not cloning the request: HTTP requests are immutable. Never modify
req.headersdirectly. Always usereq.clone({...}).
-
Guard logic in components: Checking
if (user.role === 'admin')inside a component is wrong. This logic belongs in a guard.
10. MCQs with Answers
Question 1
What is the purpose of a Route Guard?
Question 2
Which guard interface is used to prevent accessing a route?
Question 3
What does a guard return to allow navigation?
Question 4
What does a guard return to block navigation and redirect?
Question 5
What is an HTTP Interceptor?
Question 6
What is the most common use case for an HTTP Interceptor?
Question 7
Why must HTTP requests be cloned in an interceptor before modification?
Question 8
What HTTP status code typically indicates an expired or invalid token?
Question 9
What is the modern, class-free way to write Angular guards (v15+)?
canActivate: [guard1, guard2]
Answer: b) Yes, via array.
11. Interview Questions
- Q: Explain how an HTTP Interceptor differs from adding headers manually to each service method.
- Q: How would you implement a guard that checks if a user's email is verified before allowing access?
12. Summary
Guards and Interceptors are Angular's cross-cutting concern tools. Guards protect routes declaratively without duplicating auth checks in every component. Interceptors eliminate the repetitive task of adding auth headers to every HTTP call. Together, they create a clean, centralized authentication architecture.13. Next Chapter Recommendation
Let's add motion to our application! In Chapter 23: Angular Animations, we will use Angular'sBrowserAnimationsModule to create smooth transitions, fade effects, and keyframe animations.