Created
June 9, 2020 13:57
-
-
Save keithstric/e0055836ab6ecb45a96d743660d2983c to your computer and use it in GitHub Desktop.
Loading spinner http interceptor
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Injectable } from '@angular/core'; | |
import { | |
HttpRequest, | |
HttpHandler, | |
HttpEvent, | |
HttpInterceptor, HttpResponse | |
} from '@angular/common/http'; | |
import { Observable } from 'rxjs'; | |
import {catchError, map} from 'rxjs/operators' | |
import {LoadingService} from '../../layout/services/loading/loading.service'; | |
/** | |
* This class is for intercepting http requests. When a request starts, we set the loadingSub property | |
* in the LoadingService to true. Once the request completes and we have a response, set the loadingSub | |
* property to false. If an error occurs while servicing the request, set the loadingSub property to false. | |
* @class {HttpRequestInterceptor} | |
*/ | |
@Injectable() | |
export class HttpRequestInterceptor implements HttpInterceptor { | |
constructor( | |
private _loading: LoadingService | |
) { } | |
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { | |
this._loading.setLoading(true, request.url); | |
return next.handle(request) | |
.pipe(catchError((err) => { | |
this._loading.setLoading(false, request.url); | |
return err; | |
})) | |
.pipe(map<HttpEvent<any>, any>((evt: HttpEvent<any>) => { | |
if (evt instanceof HttpResponse) { | |
this._loading.setLoading(false, request.url); | |
} | |
return evt; | |
})); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment