| Angular Core Concepts | Angular Concepts (Basics to Advanced) | |
Angular Interceptors |
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.
// 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);
}
}
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 {}
// 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');
}
}
When you call getData(), the interceptor automatically attaches the Authorization header.
You don’t need to manually set headers in every service.
| Angular Core Concepts | Angular Concepts (Basics to Advanced) | |