Angular Interceptors Use Cases šŸŽÆ

beginner
5 min

Angular Interceptors Use Cases šŸŽÆ

Welcome to our comprehensive guide on Angular Interceptors! In this tutorial, we'll dive into the world of interceptors, learn why they're important, and explore practical use cases. By the end, you'll be equipped to handle complex HTTP requests and responses with ease. šŸ’” Pro Tip: This lesson is suitable for both beginners and intermediates.

Understanding Interceptors

Interceptors in Angular are powerful services that intercept HTTP requests and responses. They provide a way to modify the outgoing requests and incoming responses, enabling you to handle common tasks such as authentication, error handling, and data transformation.

Creating an Interceptor

To create an interceptor, follow these steps:

  1. Generate a service using Angular CLI:
ng generate service interceptor-name
  1. Inside the generated interceptor service, implement the HttpInterceptor interface:
typescript
import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest } from '@angular/common/http'; export class InterceptorName implements HttpInterceptor { intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { // Your logic here } }

Use Case 1: Authentication Interceptor

Let's create an authentication interceptor that adds an Authorization header to outgoing requests if the user is logged in.

typescript
import { Injectable } from '@angular/core'; import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest } from '@angular/common/http'; import { Observable } from 'rxjs'; @Injectable() export class AuthInterceptor implements HttpInterceptor { intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { const token = localStorage.getItem('token'); // Assuming you're storing the user token if (token) { const authReq = req.clone({ setHeaders: { Authorization: `Bearer ${token}` } }); return next.handle(authReq); } return next.handle(req); } }

Use Case 2: Error Interceptor

In this example, we'll create an error interceptor to handle HTTP errors and display a custom error message to the user.

typescript
import { Injectable } from '@angular/core'; import { HttpErrorResponse, HttpEvent, HttpHandler, HttpInterceptor, HttpRequest } from '@angular/common/http'; import { Observable, throwError } from 'rxjs'; import { catchError } from 'rxjs/operators'; @Injectable() export class ErrorInterceptor implements HttpInterceptor { intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { return next.handle(req).pipe(catchError(error => { let errorMessage = ''; if (error instanceof HttpErrorResponse) { errorMessage = error.message; } console.error(errorMessage); alert(errorMessage); return throwError(errorMessage); })); } }

Registering Interceptors

To use your custom interceptors, you need to register them in the app.module.ts file:

typescript
import { NgModule } from '@angular/core'; import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http'; import { AuthInterceptor, ErrorInterceptor } from './interceptors'; @NgModule({ imports: [ HttpClientModule, ], providers: [ { provide: HTTP_INTERCEPTORS, useClass: AuthInterceptor, multi: true }, { provide: HTTP_INTERCEPTORS, useClass: ErrorInterceptor, multi: true }, ] }) export class AppModule { }

šŸ“ Note: The multi: true option allows multiple interceptors to be chained and handle requests.

Wrapping Up

Interceptors are an essential part of Angular for handling various aspects of HTTP requests and responses. By creating and registering custom interceptors, you can streamline authentication, error handling, and more, making your applications more robust and efficient. āœ…

Quiz

Quick Quiz
Question 1 of 1

Which interface should an Angular interceptor implement?