Skip to main content
Angular Basics
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 CanActivate guard 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
1
ng g guard auth
auth.guard.ts
12345678910111213141516171819
import { Injectable } from '@angular/core';
import { CanActivate, Router, ActivatedRouteSnapshot } from '@angular/router';
import { AuthService } from './auth.service';

@Injectable({ providedIn: 'root' })
export class AuthGuard implements CanActivate {
  constructor(private authService: AuthService, private router: Router) {}

  canActivate(route: ActivatedRouteSnapshot): boolean {
    const token = this.authService.getToken();

    if (!token) {
      // Not authenticated — redirect to login
      this.router.navigate(['/login']);
      return false;
    }
    return true;
  }
}
app.routes.ts
1234567891011121314
const routes: Routes = [
  { path: 'login', component: LoginComponent },
  {
    path: 'dashboard',
    component: DashboardComponent,
    canActivate: [AuthGuard]   // Protected!
  },
  {
    path: 'admin',
    component: AdminComponent,
    canActivate: [AuthGuard, RoleGuard],  // Multiple guards!
    data: { role: 'admin' }    // Pass role requirement
  }
];

4. Role-Based Guard

role.guard.ts
1234567891011121314
@Injectable({ providedIn: 'root' })
export class RoleGuard implements CanActivate {
  constructor(private authService: AuthService, private router: Router) {}

  canActivate(route: ActivatedRouteSnapshot): boolean {
    const requiredRole = route.data['role'];  // Get expected role from route

    if (!this.authService.hasRole(requiredRole)) {
      this.router.navigate(['/unauthorized']);
      return false;
    }
    return true;
  }
}

5. Functional Guards (Modern Angular)

Modern Angular (v15+) supports guard functions instead of classes:
auth.guard.ts
12345678910111213
import { inject } from '@angular/core';
import { CanActivateFn, Router } from '@angular/router';
import { AuthService } from './auth.service';

export const authGuard: CanActivateFn = (route, state) => {
  const authService = inject(AuthService);
  const router = inject(Router);

  if (authService.getToken()) {
    return true;
  }
  return router.createUrlTree(['/login']);
};
typescript
12
// In routes
{ path: 'dashboard', component: DashboardComponent, canActivate: [authGuard] }

6. HTTP Interceptor — Auto Token Injection

bash
1
ng g interceptor auth
auth.interceptor.ts
1234567891011121314151617181920212223
import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from '@angular/common/http';
import { Observable } from 'rxjs';
import { AuthService } from './auth.service';

@Injectable()
export class AuthInterceptor implements HttpInterceptor {
  constructor(private authService: AuthService) {}

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    const token = this.authService.getToken();

    if (token) {
      // Clone the request and add the Authorization header
      const authReq = req.clone({
        headers: req.headers.set(&#039;Authorization&#039;, `Bearer ${token}`)
      });
      return next.handle(authReq);
    }

    return next.handle(req);
  }
}

7. Global Error Handling Interceptor

typescript
12345678910111213141516171819202122
import { catchError, throwError } from &#039;rxjs&#039;;
import { Router } from &#039;@angular/router&#039;;

@Injectable()
export class ErrorInterceptor implements HttpInterceptor {
  constructor(private router: Router, private authService: AuthService) {}

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return next.handle(req).pipe(
      catchError(error => {
        if (error.status === 401) {
          // Token expired — logout and redirect
          this.authService.logout();
        }
        if (error.status === 500) {
          console.error(&#039;Server Error:&#039;, error.message);
        }
        return throwError(() => error);
      })
    );
  }
}

8. Registering Interceptors

app.config.ts
123456789
import { provideHttpClient, withInterceptors } from &#039;@angular/common/http&#039;;

export const appConfig = {
  providers: [
    provideHttpClient(
      withInterceptors([authInterceptorFn, errorInterceptorFn])
    )
  ]
};

9. Common Mistakes

  • Not cloning the request: HTTP requests are immutable. Never modify req.headers directly. Always use req.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+)?

Q10. Can you apply multiple guards to a single route? a) No b) Yes, by passing an array to 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's BrowserAnimationsModule to create smooth transitions, fade effects, and keyframe animations.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·