Skip to content

Instantly share code, notes, and snippets.

@YonathanMeguira
Created January 31, 2018 12:31
Show Gist options
  • Save YonathanMeguira/2fbc3f4e556aaa78d187784beb5c930d to your computer and use it in GitHub Desktop.
Save YonathanMeguira/2fbc3f4e556aaa78d187784beb5c930d to your computer and use it in GitHub Desktop.
http interceptor
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import {
HttpEvent,
HttpHandler,
HttpInterceptor,
HttpRequest
} from '@angular/common/http';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
import { catchError, finalize, map } from 'rxjs/operators';
import 'rxjs/add/observable/throw';
@Injectable()
export class HTTPStatus {
private requestInFlight$: BehaviorSubject<boolean>;
constructor() {
this.requestInFlight$ = new BehaviorSubject(false);
}
setHttpStatus(inFlight: boolean) {
this.requestInFlight$.next(inFlight);
}
getHttpStatus(): Observable<boolean> {
return this.requestInFlight$.asObservable();
}
}
@Injectable()
export class HTTPListener implements HttpInterceptor {
constructor(private status: HTTPStatus) {}
intercept(
req: HttpRequest<any>,
next: HttpHandler
): Observable<HttpEvent<any>> {
return next.handle(req).pipe(
map(event => {
return event;
}),
catchError(error => {
return Observable.throw(error);
}),
finalize(() => {
this.status.setHttpStatus(false);
})
)
}
}
@hariharana
Copy link

constructor() {
    this.requestInFlight$ = new BehaviorSubject(false);
    this.noInFlight = 0 ;
  }

  setHttpStatus(inFlight: boolean) {
    if(inFlight){
      this.noInFlight++;
      this.requestInFlight$.next(inFlight);
    } else if(!inFlight && this.noInFlight == 1){
      this.noInFlight--;
      this.requestInFlight$.next(inFlight);
    } else if(!inFlight && this.noInFlight > 1){
      this.noInFlight--;
    }
  }

To Track Multiple requests inflight

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment