Making HTTP requests in Angular is straightforward, but handling authentication tokens, error responses, loading states, and request transformations across an entire application can become tedious. That's where HTTP Interceptors come in. They're one of my favorite Angular features because they let you handle all this cross-cutting concerns in one place.
Angular HTTP Client is built on RxJS Observables, which makes it perfect for handling asynchronous operations. Interceptors are middleware that sit between your application and the HTTP backend. They can modify requests (add headers, transform data), handle responses (transform data, catch errors), and implement features like authentication, logging, and caching globally.
What are Angular HTTP Interceptors?
Angular HTTP Interceptors provide:
- Request Interception - Modify requests before they're sent
- Response Interception - Transform responses before they reach components
- Error Handling - Catch and handle errors globally
- Authentication - Add tokens automatically to all requests
- Caching - Cache responses to improve performance
- Logging - Log all HTTP requests and responses
- Transformation - Transform request/response data
Setting Up HttpClient
First, import HttpClientModule in your Angular module:
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { HttpClientModule } from '@angular/common/http';
import { AppComponent } from './app.component';
@NgModule({
imports: [
BrowserModule,
HttpClientModule
],
declarations: [AppComponent],
bootstrap: [AppComponent]
})
export class AppModule { }
Basic HTTP Service
Create a service using HttpClient:
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { environment } from 'src/environments/environment';
@Injectable({
providedIn: 'root'
})
export class BusinessService {
private url: string;
constructor(private http: HttpClient) {
this.url = `${environment.ApiUrl}business`;
}
public GetBusinesses(data: any): Observable<any> {
return this.http.post(`${this.url}/get`, data);
}
public GetBusiness(businessId: number): Observable<any> {
return this.http.get(`${this.url}/${businessId}/details`);
}
}
Authentication Interceptor
Add authentication headers automatically to all requests:
import { Injectable } from '@angular/core';
import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest } 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 authToken = this.authService.getToken();
if (authToken) {
const cloned = req.clone({
setHeaders: {
Authorization: `Bearer ${authToken}`
}
});
return next.handle(cloned);
}
return next.handle(req);
}
}
// Register in app.module.ts
import { HTTP_INTERCEPTORS } from '@angular/common/http';
providers: [
{
provide: HTTP_INTERCEPTORS,
useClass: AuthInterceptor,
multi: true
}
]
Best Practices
- Use interceptors for cross-cutting concerns
- Handle errors globally with error interceptors
- Add authentication headers automatically
- Implement request/response logging
- Cache responses for better performance
- Transform data consistently
📖 Read the Complete Guide
This is just a brief overview! The complete guide on my blog includes:
- ✅ Error Handling Interceptor - Global error handling patterns
- ✅ Response Transformation - Transform responses before components
- ✅ Request Transformation - Modify requests before sending
- ✅ Caching Interceptor - Cache responses for performance
- ✅ Logging Interceptor - Log all HTTP requests/responses
- ✅ Loading State Interceptor - Manage loading states globally
- ✅ Token Refresh - Automatic token refresh on expiry
- ✅ Real-world examples from production applications
👉 Read the full article with all code examples here
What's your experience with Angular HTTP Interceptors? Share your tips in the comments! 🚀
For more Angular guides, check out my blog covering Services, Routing, Guards, and more.
Top comments (0)