| Angular Core Concepts :👈 | 👉:Angular Concepts (Basics to Advanced) |
Angular Interceptors |
What is an Interceptor in Angular?
An HTTP interceptor is a special Angular service that lets you inspect, modify, or handle HTTP requests and responses globally before they reach the server or the application code.
Interceptors are part of Angular’s HttpClientModule and implement the HttpInterceptor interface.
Key Uses of Interceptors
- Add headers: e.g., authentication tokens (JWT).
- Log HTTP traffic: useful for debugging.
- Handle errors: catch HTTP errors in one place.
- Transform requests/responses: modify data before sending or after receiving.
- Caching: store responses to reduce network calls.
How Interceptors Work
- Angular maintains a chain of interceptors.
- Each HTTP request passes through this chain before leaving the app.
- Each HTTP response passes back through the interceptors before being delivered to your service/component.
Example: Auth Token Interceptor
1. Create the Interceptor
// auth.interceptor.ts
import { Injectable } from '@angular/core';
import {
HttpInterceptor,
HttpRequest,
HttpHandler,
HttpEvent
} from '@angular/common/http';
import { Observable } from 'rxjs';
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
intercept(
req: HttpRequest,
next: HttpHandler
): Observable<HttpEvent<any>> {
// Example: Add Authorization header
const authToken = 'my-secret-jwt-token';
// Clone request and add header
const authReq = req.clone({
setHeaders: {
Authorization: `Bearer ${authToken}`
}
});
console.log('Intercepted HTTP request:', authReq);
// Pass the cloned request instead of the original
return next.handle(authReq);
}
}
2. Provide the Interceptor
Add it in your app module (or a core module):
// app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
import { AppComponent } from './app.component';
import { AuthInterceptor } from './auth.interceptor';
@NgModule({
declarations: [AppComponent],
imports: [BrowserModule, HttpClientModule],
providers: [
{
provide: HTTP_INTERCEPTORS,
useClass: AuthInterceptor,
multi: true // Important: allows multiple interceptors
}
],
bootstrap: [AppComponent]
})
export class AppModule {}
3. Use HttpClient in a Service
// api.service.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable({ providedIn: 'root' })
export class ApiService {
constructor(private http: HttpClient) {}
getData() {
return this.http.get('https://api.example.com/data');
}
}
4. Result
When you call getData(), the interceptor automatically attaches the Authorization header.
You don’t need to manually set headers in every service.
✅ Summary
- Interceptors are powerful for global request/response handling.
- You can chain multiple interceptors.
- Commonly used for auth, logging, error handling, caching, and request transformation.
| Angular Core Concepts :👈 | 👉:Angular Concepts (Basics to Advanced) |