Creating an Http interceptor in Ionic 3 and Angular 4 to display a loading indicator for every API request

One of my current challenges involves creating a custom HTTP interceptor to manage loading and other additional functions efficiently. Manually handling loading for each request has led to a considerable increase in code.

The issue at hand: The loader is being activated with every request, but the loading.dismiss() function does not seem to work as expected. Despite no errors, the loading spinner remains active.

Here's an overview of my configuration:

HTTP Interceptor:

@Injectable()
export class MyHttpWrapper extends Http {
  private loading: any;

  constructor(connectionBackend: ConnectionBackend, requestOptions: RequestOptions,private loadingCtrl: LoadingController) {
    super(connectionBackend, requestOptions);
  }

  public get(url: string, options?: RequestOptionsArgs): Observable<Response> {
    this.showLoader();

    return super.get(url, this.getRequestOptionArgs(options))
      .finally<Response>(() => {
        this.hideLoader();
      });
  }
  // Other methods omitted for brevity

app.module.ts

export function httpInterceptorFactory(xhrBackend: XHRBackend, requestOptions: RequestOptions, loadingCtrl: LoadingController) {
  return new MyHttpWrapper(xhrBackend, requestOptions, loadingCtrl);
}
    @NgModule({
      declarations: [
        MyApp
      ],
      imports: [
        BrowserModule,
        HttpModule,
        IonicModule.forRoot(MyApp),
        IonicStorageModule.forRoot()
      ],
      bootstrap: [IonicApp],
      entryComponents: [
        MyApp
      ],
      providers: [
        StatusBar,
        SplashScreen,
        {provide: ErrorHandler, useClass: IonicErrorHandler},
        {provide: APP_CONFIG, useValue: AppConfig},
        {
          provide: Http,
          useFactory: httpInterceptorFactory,
          deps: [XHRBackend, RequestOptions, LoadingController]
        }
      ]
    })
    export class AppModule {}

UPDATE:

After attempting to integrate a simple service (utilized within MyHttpWrapper), the problem persists without any changes in behavior. It seems like the issue lies elsewhere.

@Injectable()
export class LoadingService {
  private loading:any;

  constructor(private loadingCtrl: LoadingController) {

  }

  show() {
    if(!this.loading){
      this.loading = this.loadingCtrl.create({
        dismissOnPageChange: true
      });
    }
    this.loading.present();
  }
  hide() {
    if (this.loading) {
      this.loading.dismiss();
    }
  }
}

Answer №1

I have implemented a custom HTTP interceptor in my Ionic 3 application.

Below is the code for loader.ts

import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';
import { LoadingController } from 'ionic-angular';

@Injectable()
export class LoaderProvider {

  constructor(public http: Http, public loadingCtrl: LoadingController) {

  }

  loading: any = this.loadingCtrl.create({
    content: "Please wait..."
  })

  show() {
    this.loading.present();
  }

  hide() {
    this.loading.dismiss();
  }


}

This code snippet represents the implementation of an HTTP interceptor.

import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map';
import 'rxjs/Rx';

import { LoaderProvider } from '../loader/loader';

/*

Ionic 3 HTTP interceptor
Author: iSanjayAchar (@iSanjayAchar) <<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ef9c8e81858e968c878e9daf88828e868389cea18285">[email protected]</a>>

*/

@Injectable()

export class httpService {

  baseUrl: string = 'https://yourbaseurl.in'

  constructor(public http: Http, private loader: LoaderProvider) {

  }

  get(url) {
    this.loader.show();
    return this.http.get(this.baseUrl + url)
      .map(resp => resp.json())
      .finally(() => {
        this.loader.hide();
      });
  }

  post(url, body) {
    this.loader.show();
    return this.http.post(this.baseUrl + url, body)
      .map(resp => resp.json())
      .finally(() => {
        this.loader.hide();
      });
  }

  put(url, body) {
    this.loader.show();
    return this.http.put(this.baseUrl + url, body)
      .map(resp => resp.json())
      .finally(() => {
        this.loader.hide();
      });
  }

  delete(url) {
    this.loader.show();
    return this.http.delete(this.baseUrl + url)
      .map(resp => resp.json())
      .finally(() => {
        this.loader.hide();
      });
  }

  patch(url, body) {
    this.loader.show();
    return this.http.patch(this.baseUrl + url, body) 
      .map(resp => resp.json())
      .finally(() => {
        this.loader.hide();
      });
  }
}

To use the custom HTTP interceptor, import it instead of http in your components as demonstrated below

import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import { Http, Headers, RequestOptions } from '@angular/http';
import { ToastController } from 'ionic-angular';
import 'rxjs/add/operator/map';
import { AlertController } from 'ionic-angular';
import { httpService } from '../../providers/http/http';

/**
 * Generated class for the LoginPage page.
 *
 * See http://ionicframework.com/docs/components/#navigation for more info
 * on Ionic pages and navigation.
 */

@IonicPage()

@Component({
  selector: 'page-login',
  templateUrl: 'login.html',
})

export class LoginPage {
  isLoginIn: boolean = false;

  user: any = {
    email: '',
    password: ''
  }


  constructor(private http: httpService, private toast: ToastController) {

  }

 login() {

    this.http.post('/api/v1/login/', this.user)
      .subscribe(resp => {

          //Your logic

      }, err => {

         //Your logic

      }
  }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The missing async pipe has caused an error in Spartacus when attempting to lazily load CMS components

Having trouble implementing Lazy Loading of CMS Components, I encountered the following error: ERROR Error: The pipe 'async' could not be found! It works perfectly with CSR, but SSR is giving issues. Using Spartacus 3.2.2 and Angular 10.2.3 in ...

Error: Uncaught TypeError in AuthContext in Next.js 13.0.6 when using TypeScript and Firebase integration

I'm currently trying to display a page only if the user is present in my app. Right now, the app is pretty bare bones with just an AuthContext and this one page. I had it working in React, but ran into some issues when I switched it over to TS and Nex ...

Deciding between Document.createElement() and Document.createTextNode() in Javascript

I'm currently exploring the distinctions between these two code snippets: // first one var h1 = document.createElement('h1'); var t = document.createTextNode('hello'); h1.appendChild(t); document.body.appendChild(h1); // second o ...

Is it possible to identify the form triggering the ajax call within a callback function?

There are multiple forms on my website that share the same structure and classes. The objective is to submit form data to the server using the POST method, and display an error message if any issues arise. Here's how the HTML code for the forms look ...

Encountered an error while trying to create module kendo.directives using JSPM

I am attempting to integrate Kendo UI with Angular in order to utilize its pre-built UI widget directives. After running the command jspm install kendo-ui, I have successfully installed the package. In one of my files, I am importing jQuery, Angular, and ...

Press the smiley icon and drag it into the designated input box

Is there a way to select and copy a smiley/emoji from a list and paste it into an input field? Although the Inspect Element Q (console log) shows that the emoji is being clicked, I am having trouble transferring it to the input field. Here is the HTML cod ...

Vue: Customize data based on userAgent

As a newcomer to VUE, I am attempting to dynamically modify the disabled value based on the userAgent in order to display or hide the paymentMethod: data() { return { paymentMothods: [ { name: 'Visa che ...

Building a custom onChange event handler in Formik allows for greater

I want to modify the onChange function in formik input so that it converts the value from a string to a number. However, I'm unable to change the behavior as expected and the console.log doesn't show up on the screen. It seems like Formik's ...

Retrieve and manipulate the HTML content of a webpage that has been loaded into a

Hey, let's say I have a main.js file with the following code: $("#mirador").load("mirador.html"); This code loads the HTML content from mirador.html into index.html <div id="mirador"></div> I'm wondering if there is a way to chan ...

How can we access a value within a deeply nested JSON object in Node.js when the key values in between are not

In the nested configuration object provided below, I am seeking to retrieve the value associated with key1, which in this case is "value1". It's important to note that while key1 remains static, the values for randomGeneratedNumber and randomGenerated ...

Utilize JavaScript to parse JSON containing multiple object settings

After receiving the server's response, I am looking to extract the "result" from the JSON data provided. This is my JSON Input: { "header":{ "type":"esummary", "version":"0.3" }, "result":{ "28885854":{ "uid":"28885854", "pub ...

Issue with Next-Auth getServerSession failing to fetch user data in Nextjs 13.4 API Route

Having an issue with accessing user session data in a Next-Auth/Nextjs 13.4 API Route. I've set up the JWT and Session callback, but the user data defined in the callback function isn't translating correctly to what getServerSession is fetching i ...

Create a URL hyperlink using javascript

I am looking to create a link to a page that updates its URL daily. The main URL is where X represents the day of the month. For example, for today, July 20th, the link should read: In my JavaScript section, I currently have code that retrieves the cur ...

"Standard" approach for a Date instance

During my time in the Node REPL environment, the following output was displayed: > console.log(new Date()) 2023-08-15T09:21:45.762Z undefined > console.log(new Date().toString()) Sun Aug 15 2023 09:21:50 GMT+0000 (Coordinated Universal Time) undefine ...

Guide on determining if the value in a JSON object is a string or an array in Node.js

Running a Node.js application, I encountered the following JSON array structure. First JSON object: var json1= { bookmarkname: 'My Health Circles', bookmarkurl: 'http://localhost:3000/', bookmark_system_category: [ '22&apos ...

Transform a row in an ng Smart table to a routerlink using Angular 2

I've been exploring ng2 Smart Table and I'm looking to convert a row (or even cell data) into a clickable link using routerlink. The current method I'm employing to retrieve some of my row's data is as follows: onUserRowSelect(event) ...

Issue with Domsanitizer bypasssecuritytruststyle functionality on Internet Explorer 11 not resolving

CSS:- Implementing the style property from modalStyle in TypeScript <div class="modal" tabindex="1000" [style]="modalStyle" > Angular Component:- Using DomSanitizer to adjust height, display, and min-height properties. While this configuration work ...

Here is a unique rewrite: "Strategies for effectively passing the data variable in the geturldata function within Vue.js on the HTML side vary

How can I properly pass a variable in the getdataurl function in Vue.js? I need help with passing a variable in getdataurl function in Vue.js. Please provide a clear explanation and include as much detail as possible. I have tried doing some background r ...

In Node.js, the `res.send()` function is called before the actual functionality code is executed

As a newcomer to node js, I am currently working on an app where I query the MySql DB and process the results using node js. One issue I have encountered is that if my initial query returns null data, I then need to perform another query and further proc ...

The Angular test spy is failing to be invoked

Having trouble setting up my Angular test correctly. The issue seems to be with my spy not functioning as expected. I'm new to Angular and still learning how to write tests. This is for my first Angular app using the latest version of CLI 7.x, which i ...