HTTP Interceptors
HTTP interceptors are a powerful feature in Angular that allow you to intercept and modify HTTP requests and responses. This guide covers the basics of setting up and using HTTP interceptors in your Angular application.
Setting Up HTTPClientModule
First, import the HttpClientModule
into your app module:
// app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
import { AppComponent } from './app.component';
import { DataService } from './data.service';
import { HomeComponent } from './home/home.component';
import { AuthInterceptor } from './auth.interceptor';
@NgModule({
declarations: [AppComponent, HomeComponent],
imports: [BrowserModule, HttpClientModule],
providers: [
DataService,
{ provide: HTTP_INTERCEPTORS, useClass: AuthInterceptor, multi: true }
],
bootstrap: [AppComponent]
})
export class AppModule { }
Creating an Interceptor
Create an interceptor to manage HTTP requests using the Angular CLI command:
$ ng generate interceptor auth
This command generates a new interceptor file named auth.interceptor.ts
.
Implementing the Interceptor
In the interceptor file, implement the HttpInterceptor
interface and define the intercept
method:
// auth.interceptor.ts
import { Injectable } from '@angular/core';
import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest } from '@angular/common/http';
import { Observable } from 'rxjs';
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
intercept(req: HttpRequest, next: HttpHandler): Observable> {
const authToken = 'my-auth-token';
const authReq = req.clone({
setHeaders: { Authorization: `Bearer ${authToken}` }
});
return next.handle(authReq);
}
}
Using the Interceptor
HTTP interceptors are automatically applied to all HTTP requests made using the HTTPClient. You don't need to do anything special in your components to use them. Here's an example component that makes HTTP requests:
// home.component.ts
import { Component, OnInit } from '@angular/core';
import { DataService } from '../data.service';
@Component({
selector: 'app-home',
template: `
Posts
- {{ post.title }}
`
})
export class HomeComponent implements OnInit {
posts: any[] = [];
constructor(private dataService: DataService) {}
ngOnInit() {
this.dataService.getPosts().subscribe(data => {
this.posts = data;
});
}
}
Handling Errors in Interceptors
You can also handle errors in interceptors using the catchError
operator from RxJS:
// auth.interceptor.ts
import { Injectable } from '@angular/core';
import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest, HttpErrorResponse } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { catchError } from 'rxjs/operators';
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
intercept(req: HttpRequest, next: HttpHandler): Observable> {
const authToken = 'my-auth-token';
const authReq = req.clone({
setHeaders: { Authorization: `Bearer ${authToken}` }
});
return next.handle(authReq).pipe(
catchError((error: HttpErrorResponse) => {
console.error('Error from interceptor', error);
return throwError('Something went wrong');
})
);
}
}
Key Points
- HTTP interceptors allow you to intercept and modify HTTP requests and responses.
- Import
HttpClientModule
in your app module to set up the HTTP Client. - Create an interceptor by implementing the
HttpInterceptor
interface. - Use interceptors to set headers, handle errors, and perform other tasks on HTTP requests and responses.
- Register interceptors in your app module using the
HTTP_INTERCEPTORS
token.
Conclusion
HTTP interceptors are a powerful tool for managing HTTP requests and responses in Angular. By setting up interceptors, you can enhance your application's capabilities and improve its robustness. Happy coding!