Disable the loader for a specific method that was implemented in the Interceptor

Custom Loader Interceptor A loader has been implemented within an Interceptor. I have a specific requirement where the loader should not be triggered during the upload() function. It should not be applied to that particular method only.

export class CustomLoaderInterceptor implements HttpInterceptor {

  constructor(private customLoaderService: LoaderService) { }
  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    this.customLoaderService.show();
    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    this.customLoaderService.show();
    return next.handle(req).pipe(map(event => {
        if (event instanceof HttpResponse) {
           this.customLoaderService.hide();
        }         
        return event;
    }));
}
  }
}

custom-loader.service.ts This service includes methods to start and stop the spinner.

 export class CustomLoaderService {
      isLoading = new Subject<boolean>();
      constructor() { }
      show() {
    
        this.isLoading.next(true);
      }
      hide() {
        this.isLoading.next(false);
      }
     }

MyUploadService
In the following method where I invoke upload(), I need to prevent the loader from displaying.

upload(file: File,id) {
    const formData: FormData = new FormData();
    formData.append('file', file);
    return this.http.post(`${this.baseURL}/fileupload/${id}`, formData,{
      reportProgress: true,
      observe: 'events'
    });
  }

Answer №1

Consider including an extra parameter in your request:

    const options = new HttpHeaders().set('Show-Spinner', 'true');
    
    return this.http.get(url, { headers: options });

You can then access this parameter in your interceptor:

    const showSpinner = req.headers.get('Show-Spinner');
    
    if (showSpinner) {
        this.showLoading.next(true);
        // Make sure to remove this parameter afterwards:
        req = req.clone({ headers: req.headers.delete('Show-Spinner','true') });
    }

Answer №2

Revise your interceptor implementation

export class LoaderInterceptorService implements HttpInterceptor {

    constructor(private loaderService: LoaderService) { }

    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

        if(request.url.match(/^\/fileupload/)) {
            return next.handle(req);
        }

        this.loaderService.show();
        return next.handle(req).pipe(map(event => {
            if (event instanceof HttpResponse) {
                this.loaderService.hide();
            }
            return event;
        }));
    }

}

Answer №3

As per the discussion on Enabling transmission of miscellaneous data to HTTP client options in #18155, it appears that this issue is still unresolved.

There are some workarounds available:

  • One approach involves using HttpClient and adding metadata by manipulating HTTP Headers.

Myuploadservice.ts

return this.http.post(`${this.baseURL}/fileupload/${id}`, formdata,{
  reportProgress: true,
  observe: 'events',
  headers: { hideLoader: 'true' } // add header param
});

loader-interceptor.ts

intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    
   if (req.headers.has('hideLoader')) {
    const headers = req.headers.delete('hideLoader');
    req = req.clone({ headers });
   } else{
    this.loaderService.show();
   }
    return next.handle(req).pipe(map(event => {
        if (event instanceof HttpResponse) {
           this.loaderService.hide();
        }         
        return event;
    }));

Guide on passing metadata for interceptors to Angular HttpClient

// MyRequestOptions is a remnant from a preivous implementation that redeclared HttpRequestOptonArgs with more props

export interface MyRequestOptions {
  skipErrorHandler?: boolean;
  hideLoader?: boolean;
  external?: boolean;
  suppressError?: boolean;
  ignoreSomething?: boolean;
}

const LoadInterceptorMeta = (options: MyRequestOptions): {params: HttpParamsWithMeta} => {
  const params: HttpParamsWithMeta = withMeta();
  const {skipErrorHandler, suppressError, external, hideLoader, ignoreCrId} = options;

  [
    new LoaderInterceptorConfig(hideLoader),
    new ExernalInterceptorConfig(external),
    new ErrorInterceptorConfig(skipErrorHandler, suppressError),
    new SomethingInterceptorConfig(ignoreSomething)
  ].forEach(interceptor => params.meta.add(interceptor));

  return {params};
};

@Injectable({
  providedIn: 'root'
})
export class HttpFacetService {

  constructor(private http: HttpClient) { }

  get(url: string, options: MyRequestOptions) {
    return this.http.get(url, LoadInterceptorMeta(options));
  }

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

Bringing in Leaflet for Angular 2 and beyond

Hello there! I'm currently diving into the world of Angular 2 and wanting to figure out how to integrate Leafletjs with it. My goal is to set up Leafletjs without having to directly include JS and CSS in my index.html file. Additionally, I want to ens ...

Tips for converting Javascript require to Typescript import using the const keyword

Recently, I've been attempting to import faktory_worker_node from github.com/jbielick/faktory_worker. The README provides the following instructions: const faktory = require('faktory-worker'); faktory.register('ResizeImage', asyn ...

Mastering the art of utilizing GSI Index and FilterExpression in AWS DynamoDB querying

In my DynamoDB database table, I have the following structure. It consists of a primary key (ID) and a sort key (receivedTime). ID(primary key) receivedTime(sort key) Data ID1 1670739188 3 ID2 167072 ...

It seems that Angular2 Universal is experiencing some instability as it crashes frequently with the message "[nodemon] app crashed - waiting for file

After trying to work with the starter repo from my Angular class, I've found it to be quite unstable. It seems to be working locally when hitting the same service as remote, but I keep encountering errors. I have followed all the instructions: npm r ...

Establishing the testing sequence for Angular 8

I've been encountering a frustrating issue where one of my tests fails at random intervals. To add some order to the debugging process, I attempted to set a seed number in the 'karma.conf.js' file and also tried setting 'random: false&a ...

Angular design pattern: organizing rows according to the month

I currently possess the following items: { "pk": 33, "name": "EVENT 634", "start_date": "2022-05-11T00:00:00", "end_date": "2022-05-14T00:00:00" }, { "pk": ...

"Exploring the differences between normalization structures and observable entities in ngrx

I'm currently grappling with the concept of "entity arrays" in my ngrx Store. Let's say I have a collection of PlanDTO retrieved from my api server. Based on the research I've done, it seems necessary to set up a kind of "table" to store th ...

Implement a concealed identification field with React-Admin within a React Native application

I'm currently working on incorporating the SimpleFormIterator from the React-Admin module in order to generate a list of child records within a parent record edit form. After setting up the SimpleFormIterator component with all the necessary details ...

Encountering issues while trying to run npm install for an Angular 7 application, specifically receiving an error stating: "Module not found: @angular-devkit/build-ng-packagr." This error is hindering

I don't have much experience with JavaScript, node, npm, Angular, etc. My expertise lies in TypeScript as I am still a beginner. However, I recently inherited an application that requires maintenance to resolve a cross-site cookie issue. As I attempt ...

How to access nested JSON elements in Javascript without relying on the eval function

Below is a JSON that I am trying to access. { "orders": { "errorData": { "errors": { "error": [ { "code": "ERROR_01", "description": "API service is down" } ] } }, "status": " ...

How can I apply concatMap in Angular?

Can you please guide me on how to effectively utilize concatMap with getPrices() and getDetails()? export class HistoricalPricesComponent implements OnInit, OnDestroy { private unsubscribe$ = new Subject < void > (); infoTitle ...

The system is unable to locate a compatible object with the identifier '[object Object]' of type 'object'. NgFor is limited to binding with iterables like Arrays, not JSON data

Working with JSON data data:[ { assets:[[tool_order_id: "38",order_status_id: "10"]], order_info:[id: "1", order_type: "6",check: "1", current_Stage_id: "29"] }, { assets:[tool_order_ ...

Having trouble displaying nested routes in Angular within the view

I'm encountering some issues with child/nested routes in Angular 4. In the app.module.ts file, my imports statement looks like this: RouterModule.forRoot([ { path: 'templates', component: TemplateLandingC ...

A guide on implementing directives in Angular 2

I am trying to load my navbar.html in my app.component.html by using directives and following the method below: Here is my navbar html: <p>Hi, I am a pen</p> This is my navbar.ts: import {Component, Directive, OnInit} from '@angular/c ...

Importing CSS into the styles section of angular.json is no longer feasible with Angular 6

Currently in the process of migrating a project to Angular 6, I'm facing an issue with importing my CSS file within the styles section of angular.json: "styles": [ "./src/styles.css", "./node_modules/primeng/resources/primeng.min.css", ...

The error message indicates that the property `v.context.$implicit` is not callable

I am a beginner with Typescript and it has only been 3 days. I am trying to access data from Firebase and display it in a list. However, I keep encountering an error when trying to navigate to another page using (Click) ="item ()". Can someone point out wh ...

Issues with the inheritance functionality in styled components are causing errors

The issue arises when I try to customize the styling of my PrimaryButton component, separate from the DefaultButton. Despite writing style properties for it, the changes do not take effect. Here is the folder structure: https://i.stack.imgur.com/0KjyH.pn ...

The NGRX state in Angular is not being properly saved by the local storage

Currently, I am utilizing NGRX for state management within my Angular application. While NGRX is functioning correctly, I have encountered an issue with using local storage to persist the NGRX state. Upon refreshing the browser, the NGRX data reverts back ...

Can you provide a visual depiction of the paths in my app?

Do you know of a tool that can assist in creating visual or graphical representations of the pathways within my angular 6 application? ...

The complete Angular 2 application fails to load when accessed using a custom domain name

I've been struggling for the past few days trying to solve a strange issue. When I try to access my Angular 2 app using a domain name (example.com), it gets stuck on the loading screen. However, if I try accessing the same app without nginx, it loads ...