Ionic 7+ Angular LoadingController with Http Interceptor Loader Present and Dismiss issue

27 Views Asked by At

Issue Description:

I'm encountering an issue with the LoadingController in Ionic 7 when used in conjunction with an HttpInterceptor. The LoadingController is not being presented or dismissed correctly in certain scenarios.

Steps to Reproduce:

With this logic in interceptor and with 2 call Api you will see the error that the loading dose't dismiss correctly

The loading spinner should be dismissed when the HTTP request completes or encounters an error.

import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest, HttpResponse } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { LoadingController } from '@ionic/angular';
import { TranslateService } from '@ngx-translate/core';
import { Observable } from 'rxjs';
import { tap } from 'rxjs/operators';

@Injectable({
  providedIn: 'root'
})
export class LoaderInterceptor implements HttpInterceptor {
  private loading: boolean = false;

  constructor(
    private loadingController: LoadingController,
    private readonly translateService: TranslateService
  ) {}

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    this.presentLoading();
    return next.handle(req).pipe(
      tap(
        (event: HttpEvent<any>) => {
          this.dismissLoading();

        },
        (err: any) => {
          this.dismissLoading();
        }
      )
    );
  }

  private async presentLoading() {
    if (!this.loading) {
      this.loading = true

      const load = await this.loadingController.create({
        message: this.translateService.instant("LOADING")
      });
      await load.present();
    }
  }

  private async dismissLoading() {

    if (this.loading) {
      this.loading = false;

      await this.loadingController.dismiss();
    }
  }
}

0

There are 0 best solutions below