Skip to content

Instantly share code, notes, and snippets.

@Sathasivamthirumoorthi
Created July 25, 2023 08:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Sathasivamthirumoorthi/a913de0017372f2bbafe40808863fadd to your computer and use it in GitHub Desktop.
Save Sathasivamthirumoorthi/a913de0017372f2bbafe40808863fadd to your computer and use it in GitHub Desktop.
import { Injectable } from '@angular/core';
import {
HttpRequest,
HttpHandler,
HttpEvent,
HttpInterceptor
} from '@angular/common/http';
import { Observable } from 'rxjs';
import { finalize } from 'rxjs/operators';
import { LoaderService } from '../services/loader.service';
@Injectable()
export class LoaderInterceptor implements HttpInterceptor {
private requests: HttpRequest<any>[] = [];
constructor(private loaderService: LoaderService) { }
removeRequest(req: HttpRequest<any>) {
const i = this.requests.indexOf(req);
if (i >= 0) {
this.requests.splice(i, 1);
}
this.loaderService.isLoading.next(this.requests.length > 0);
}
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
this.requests.push(req);
this.loaderService.isLoading.next(true);
return next.handle(req).pipe(
finalize(() => {
this.removeRequest(req);
})
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment