In this article, we are going to discuss the HTTP Interceptors in Ionic.
What is an HTTP Interceptor?
HTTP interceptors are classes that implement the Http Interceptor interface. They can be used to perform various tasks related to HTTP requests and responses, such as adding headers, handling errors, modifying the request or response data, logging, authentication, etc.
Benefits of the HTTP Interceptors
-
Centralized Request Handling:
HTTP interceptor allow you to manage all HTTP requests and response in a single location, making it easier to maintain and update the code. It's remove duplicate code across all service calls.
2. Automatic Authentication and Authorization:
Interceptors can automatically add Bearer token in every API call.
3. Error Handling and Response Management:
Interceptors provide a convenient way to handle errors globally. For example, they can intercept Unthorized, redirect to a login page, or sow notification.
4. Loggin and Debugging:
Interceptors can log outgoing requests and incomming responses, making debugging easier by giving you visibility into the API interactions and any unexpected response or delays.
5. Global Headers and Configuration:
You can set headers, such as Content-Type or Accept-Language, for all outgoing requests in one place, ensuring consistency across all requests and making it easy to adjust global settings.
Implement HTTP Interceptor
import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest, HttpResponse } from "@angular/common/http";
import { Injectable } from "@angular/core";
import { catchError, map, Observable, throwError } from "rxjs";
export const InterceptorSkipHeader = 'X-Skip-Interceptor';
const TOKEN_KEY = "my-token";
@Injectable()
export class HttpTokenInterceptor implements HttpInterceptor{
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
var headerConfig = {
'Authorization':''
}
const token = localStorage.getItem(TOKEN_KEY);
if (token) {
headerConfig['Authorization'] = `Bearer ${token}`;
}
const request = req.clone({ setHeaders: headerConfig });
// if (req.headers.has(InterceptorSkipHeader)) {
// const headers = req.headers.delete(InterceptorSkipHeader);
// return next.handle(req.clone({ headers }));
// }
return next.handle(request)
.pipe(map((evt: any) => {
if (evt instanceof HttpResponse) {
}
return evt;
}), catchError((err) => {
return throwError(err);
})
)
}
}
- InterceptorSkipHeader: handle to skip any header then we are using slip header.
- TOKEN_KEY: using for access the token from localStorage
- next.handle(request): Passes the modified request down the chain of interceptors (or to the backend if no further interceptors exist).
- the Pipe used to apply transformations.
- map Operator checks if the evenet (evt) is an instance of HttpResponse. Currently, it does nothing but could be customized to handle responses.
- catchError Operator catches any error in the request or response and rethrows it with throwError(err), allowing error handling in other parts of the application.
Register the HttpTokenInterceptor as an HTTP interceptor in your Ionic Application.
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { HTTP_INTERCEPTORS } from '@angular/common/http';
import { AppComponent } from './app.component';
import { HttpTokenInterceptor } from './path-to-http-token-interceptor';
@NgModule({
declarations: [AppComponent],
imports: [BrowserModule],
providers: [
{ provide: HTTP_INTERCEPTORS, useClass: HttpTokenInterceptor, multi: true }
],
bootstrap: [AppComponent]
})
export class AppModule { }
Login to leave a comment.