Ionic 4 loading interceptor can't dismiss loading

I am trying to create an Http interceptor to display loading in all the pages. But I am not able to dismiss the loading controller

I have followed this https://www.youtube.com/watch?v=IJWCpa_-MeU But the problem is loading is displayed infinitely.

Actually I am a bit new to these concepts. So please help me out.

Thank you very much

@Injectable()
  export class HttpRequestInterceptor implements HttpInterceptor {
    constructor(
      private loadingCtrl: LoadingController,
    ) {}

    intercept(
      request: HttpRequest<any>,
      next: HttpHandler
    ): Observable<HttpEvent<any>> {
      this.loadingCtrl.getTop().then(hasLoading => {
        if (!hasLoading) {
          this.loadingCtrl.create({
            spinner: 'circular',
            translucent: true
          }).then(loading => loading.present());
        }
      });

      return next.handle(request).pipe(
        catchError(err => {
          if (err instanceof HttpErrorResponse) {
            switch ((<HttpErrorResponse>err).status) {
              case 401:
             console.log("401")

              default:
                return throwError(err);
            }
          } else {
            return throwError(err);
          }
        }),
        retryWhen(err => {
          let retries = 1;
          return err.pipe(
            delay(1000),
            tap(() => {
              // this.showRetryToast(retries);
            }),
            map(error => {
              if (retries++ === 3) {
                throw error; // Now retryWhen completes
              }
              return error;
            })
          );
        }),
        catchError(err => {
          return EMPTY;
        }),
        finalize(() => {
          this.loadingCtrl.getTop().then(hasLoading => {
            if (hasLoading) {
              this.loadingCtrl.dismiss();
            }
          });
        })
      );
    }
    }

Here is a simple Http request I made, but data is displayed in console.log but loading is not getting dismissed

ngOnInit() {

    this.cartService.getProductDetails().subscribe(data =>{

        this.products = data;
        this.filter_products = this.products;

        console.log(this.products)  

    })

Anyone please ?

I am going through a strange problem. I have just created a new project and pasted the same code. The code is working very fine.But for my current project loading isn’t getting dismissed

Hello,

Try this.

If you want to display the loader when the ionicons or the local files are called delete the first condition.

// app.modules.ts
providers: [
	...
	{provide: HTTP_INTERCEPTORS, useClass: LoaderInterceptor, multi: true}
]
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
	if (req.url.indexOf('http') !== 0) {
		return next.handle(req);
	}

	return from(this.loadingController.create())
		.pipe(
			tap((loading) => {
				return loading.present();
			}),
			switchMap((loading) => {
				return next.handle(req).pipe(
					finalize(() => {
						loading.dismiss();
					})
				);
			})
		);
}
1 Like

Don’t forget the LoadingController

constructor(private loadingController: LoadingController) {
}

Okay. I will try this approach. The problem is handling multiple http request because of async behaviour of loading control

When i try this method i see multiple loaders are getting created. How to check if the loader is already present? and create only if it is not there.