An HTTP Interceptor is a mechanism that allows you to modify HTTP requests and responses globally before they reach your app’s code or are returned to the server. This is useful for attaching authentication tokens, logging, handling errors, or caching responses without having to modify every request individually.
Why Use an Interceptor in Ionic?
Interceptors offer several advantages when used in an Ionic application:
Implementing an HTTP Interceptor in Ionic
Step 1: Create the Interceptor Service
ionic generate service services/http-interceptor
import { Injectable } from '@angular/core'; import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from '@angular/common/http'; import { Observable } from 'rxjs'; @Injectable() export class HttpInterceptorService implements HttpInterceptor { intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { // Clone the request to add the new header const clonedRequest = req.clone({ headers: req.headers.set('Authorization', 'Bearer YOUR_TOKEN_HERE') }); // Pass the cloned request instead of the original request to the next handle return next.handle(clonedRequest); } }
Step 2: Register the Interceptor
Once you’ve created the interceptor service, you’ll need to register it in your app module. Open app.module.ts
and add the interceptor to the providers array.
import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http'; import { HttpInterceptorService } from './services/http-interceptor.service'; @NgModule({ declarations: [...], imports: [ HttpClientModule, // Make sure HttpClientModule is imported ... ], providers: [ { provide: HTTP_INTERCEPTORS, useClass: HttpInterceptorService, multi: true // This is important to allow multiple interceptors } ], bootstrap: [AppComponent] }) export class AppModule { }
The beauty of interceptors is that they work both ways – for outgoing requests and incoming responses. You can handle errors globally by modifying the intercept
method in your service.
import { catchError } from 'rxjs/operators'; import { throwError } from 'rxjs'; intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { const clonedRequest = req.clone({ headers: req.headers.set('Authorization', 'Bearer YOUR_TOKEN_HERE') }); return next.handle(clonedRequest).pipe( catchError(error => { // Handle error here console.error('Error occurred:', error); return throwError(error); }) ); }
Step 4: Displaying a Global Loader
import { Injectable } from '@angular/core'; import { LoadingController } from '@ionic/angular'; @Injectable({ providedIn: 'root' }) export class LoaderService { private loading: HTMLIonLoadingElement; constructor(private loadingController: LoadingController) {} async present() { this.loading = await this.loadingController.create({ message: 'Loading...', }); await this.loading.present(); } async dismiss() { if (this.loading) { await this.loading.dismiss(); } } }
1. Authentication: Automatically attach JWT tokens or API keys to each request.
2. Error Handling: Show a unified error message to the user when a network error occurs.
3. Logging: Log request/response details for debugging or monitoring.
4. Data Transformation: Modify the incoming data format to suit your application needs.