In the below code, this.busyCount++
is called just once per call to my get method but the this.busyCount--
inside tap()
is being called multiple times. This is causing isBusy
to always be false.
What is the correct way to increment and decrement busyCount
to find out if there is an active http request.
The showBusy
parameter determines if loading spinner is displayed or not. I'm not sure how I would pass this to an interceptor or I could use the approach here.
I've tried using finalize operator to decrement but I faced the same issue.
@Injectable()
export class DataService {
constructor(private http: HttpClient) { }
public busyCount = 0;
public get isBusy(): boolean { return this.busyCount > 0; }
get<T>(relativeUrl: string, showBusy: boolean = true): Observable<T> {
if (showBusy)
this.busyCount++;
return this.http.get<T>(`${this.baseURL}${relativeUrl}`)
.pipe(
tap(s => {
if (showBusy)
this.busyCount--;
}),
catchError((err: HttpErrorResponse) => {
if (showBusy)
this.busyCount--;
return Observable.throw(err)
})
);
}
}