What is an HTTP Interceptor?
An HTTP Interceptor in Angular is a class that implements the HttpInterceptor
interface. It allows you to intercept and modify HTTP requests or responses before they are sent to the server or after they are received. This feature is particularly useful for adding common functionality to multiple HTTP requests, such as setting authentication tokens, handling errors globally, or logging request details.
Key Use Cases for HTTP Interceptors:
How to Create an HTTP Interceptor in Angular
bash Copy code ng generate service interceptors/auth
auth.service.ts
) inside the interceptors
folder.HttpInterceptor
Interface: Open the newly created service file and implement the HttpInterceptor
interface. This interface requires you to define the intercept
method, which takes an HttpRequest
and an HttpHandler
as arguments.typescript Copy code import { Injectable } from '@angular/core'; import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from '@angular/common/http'; import { Observable } from 'rxjs'; @Injectable() export class AuthInterceptorService implements HttpInterceptor { intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { // Clone the request to add the new header const clonedRequest = req.clone({ headers: req.headers.set('Authorization', `Bearer YOUR_TOKEN_HERE`) }); // Pass the cloned request instead of the original request to the next handle return next.handle(clonedRequest); } }
Authorization
header to each outgoing request.app.module.ts
).typescript Copy code import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http'; import { AuthInterceptorService } from './interceptors/auth.service'; @NgModule({ declarations: [ // Your components ], imports: [ HttpClientModule, // Other modules ], providers: [ { provide: HTTP_INTERCEPTORS, useClass: AuthInterceptorService, multi: true } ], bootstrap: [AppComponent] }) export class AppModule { }
multi: true
option allows Angular to use multiple interceptors if needed.Best Practices for Using HTTP Interceptors
Conclusion
HTTP Interceptors are a powerful tool in Angular that can help you manage HTTP requests and responses more efficiently. Whether you need to add authentication headers, log request details, or handle errors globally, interceptors provide a centralized and reusable solution. By implementing the practices outlined in this guide, you can streamline your HTTP communication and maintain a clean, maintainable codebase in your Angular applications.