Why Use an Interceptor?
Understanding Interceptors in Angular
A simple guide for beginners
🔍 What is an Interceptor?
In Angular, an Interceptor is like a middleman between your app and the server. Whenever you make an HTTP request, the interceptor can see, modify, or even stop it before it goes to the server.
It also works the other way — when the server sends a response back, the interceptor can inspect or modify it before your app receives it.
Think of it like a security guard who checks every request and response going in or out of your app.
Your App → Interceptor → Server
Server → Interceptor → Your App
⚙️ Why Use an Interceptor?
- Add an authentication token to every request automatically
- Show or hide a loading spinner while waiting for data
- Handle errors globally (e.g., “Server not available” messages)
- Log requests and responses for debugging
🧩 Step-by-Step Example
Step 1: Create a Service to Fetch Data
@Injectable({
providedIn: 'root'
})
export class DataService {
constructor(private http: HttpClient) {}
getPosts(): Observable<any> {
return this.http.get('https://jsonplaceholder.typicode.com/posts');
}
}
Step 2: Create the Interceptor
@Injectable()
export class LoadingInterceptor implements HttpInterceptor {
constructor(private loadingService: LoadingService) {}
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
this.loadingService.show();
return next.handle(req).pipe(
finalize(() => this.loadingService.hide())
);
}
}
Step 3: Loading Service
@Injectable({
providedIn: 'root'
})
export class LoadingService {
private _loading = new BehaviorSubject<boolean>(false);
public loading$ = this._loading.asObservable();
show() { this._loading.next(true); }
hide() { this._loading.next(false); }
}
Step 4: Register the Interceptor
@NgModule({
providers: [
{
provide: HTTP_INTERCEPTORS,
useClass: LoadingInterceptor,
multi: true
}
]
})
export class AppModule {}
Step 5: Component
@Component({
selector: 'app-root',
templateUrl: './app.component.html'
})
export class AppComponent implements OnInit {
posts: any[] = [];
loading = false;
constructor(private dataService: DataService, private loadingService: LoadingService) {}
ngOnInit() {
this.loadingService.loading$.subscribe(
(isLoading) => this.loading = isLoading
);
}
loadPosts() {
this.dataService.getPosts().subscribe(data => this.posts = data);
}
}
Step 6: HTML Template
<div style="text-align:center; margin-top:20px;">
<h2>Angular Interceptor Example</h2>
<button (click)="loadPosts()">Load Posts</button>
<div *ngIf="loading" style="color: blue; margin: 10px;">
<strong>Loading...</strong>
</div>
<ul *ngIf="!loading">
<li *ngFor="let post of posts">
<strong>{{ post.title }}</strong><br />
{{ post.body }}
</li>
</ul>
</div>
🧠 Summary
- ✅ Interceptors are middlemen for all HTTP requests
- ✅ You can add tokens, handle errors, and show loaders automatically
- ✅ You create them once and they work globally across your app
Interceptors make your Angular app cleaner, more secure, and easier to manage!
Comments
Post a Comment