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.
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.
To create an interceptor, follow these steps:
ng generate service interceptor-name
HttpInterceptor interface: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
}
}Let's create an authentication interceptor that adds an Authorization header to outgoing requests if the user is logged in.
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);
}
}In this example, we'll create an error interceptor to handle HTTP errors and display a custom error message to the user.
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);
}));
}
}To use your custom interceptors, you need to register them in the app.module.ts file:
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.
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. ā
Which interface should an Angular interceptor implement?