Ionic 4 | Make HTTP Calls and Handle Responses Easily Using an Interceptor

Applications with dynamic data call from REST API to get updated, these calls are mainly of POST or GET type. In Ionic 4 using Angular 7, we use HttpClientModule to make these POST or GET requests.

After Angular 4.3 the concept of Interceptors was introduced, using which we can override the HTTP calls to handle their requests and responses.

We can use Interceptors for many purposes like Handling Error responses, Internet connectivity intimations, show progress loaders, Add/ change header types of HTTP calls, secure server connectivity using token based authentications and many more.

In this post, we will learn How to make HTTP calls and handle their responses and request at one place using an Angular Interceptor.

We will create a new Ionic 4 App using Angular latest stable version 7 using the latest Ionic CLI(v4.12.0)

Before we start make sure you have latest Ionic CLI installed

Create new Ionic 4 App

Run following NPM command in CMD to create a new Ionic 4 application with a blank template.

Add HttpClientModule in App’s Module

To use HTTP services, we need to import HttpClientModule, then add in imports array in the app.module.ts file as shown below.

 

Create an Http Service to make API calls

Next, we will create a new Http Service to make API calls with a defined URL. Create a file http.service.ts under app folder or simply run following CMD command in CLI

Note: –skipTests=true option will not create test file as we don’t need them now.

Replace http.service.ts file content with the following code.

======================================

 

Create an HTTP Interceptor

Now we will create an HTTP Interceptor to globally intercept and modify calls. Create a new file httpConfig.interceptor.ts and replace below code in it.

Interceptors implements HttpInterceptor service to override the intercept method taking two parameters HttpRequest and HttpHandler.

As we can’t directly change headers of the request so we make a clone of request.

To use this interceptor globally we need to import this in the app.module.ts file and also add in providers array as shown below.

 

Show Ionic Loader Spinner on HTTP request

Using Interceptors we can easily show/ hide Ionic Spinner loader at one place. We will import LoadingController and use it show/hide in the interceptor callbacks. You can check more details on loaders here

 

So now we have an Interceptor in Ionic 4 application which is helping in modifying get requests by changing headers and also setting token in Authentication key. We are also handling errors in Interceptors which can be logged for debugging purposes.

Leave a Reply

avatar
  Subscribe  
Notify of