Is there any method like ngOnit and ngOnDestroy for httpClient method in Angular? Basically I am trying to show a spinner and hide the spinner on every httpClient call i make.
You'll need an interceptor:
Just create a Service that is responsible to set whether the Loader needs to show or hide. Set this value from your interceptor then:
import { Injectable } from "@angular/core";
import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest } 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 {
constructor(public loaderService: LoaderService) { }
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
this.loaderService.show();
return next.handle(req).pipe(
finalize(() => this.loaderService.hide())
);
}
}
Read this article for more ref.