import { Injectable , Optional , Inject } from '@angular/core' ; import { HttpInterceptor , HttpEvent , HttpHandler , HttpRequest } from '@angular/common/http' ; import { Observable } from 'rxjs' ; import { finalize } from 'rxjs/operators' ; import { NgProgress , NgProgressRef } from 'ngx-progressbar' ; import { NgProgressHttpConfig , ProgressHttpConfig , NG_PROGRESS_HTTP_CONFIG } from './ng-progress-http.interface' ; @ Injectable ( ) export class NgProgressInterceptor implements HttpInterceptor { private _inProgressCount = 0 ; private _progressRef ! : NgProgressRef ; private readonly _config : ProgressHttpConfig = { id : 'root' , silentApis : [ ] } ; constructor ( protected ngProgress , @ Optional ( ) @ Inject ( NG_PROGRESS_HTTP_CONFIG ) config ? ) { this . _config = config ? { ... this . _config , ... config } : this . _config ; } intercept ( req , next ) { if ( req . headers . has ( 'ignoreProgressBar' ) ) { return next . handle ( req . clone ( { headers : req . headers . delete ( 'ignoreProgressBar' ) } ) ) ; } if ( this . checkUrl ( req ) ) { return next . handle ( req ) ; } this . _inProgressCount ++ ; this . _progressRef = this . ngProgress . ref ( this . _config . id ) ; if ( ! this . _progressRef . isStarted ) { this . _progressRef . start ( ) ; } return next . handle ( req ) . pipe ( finalize ( ( ) => { this . _inProgressCount -- ; if ( this . _inProgressCount === 0 ) { this . _progressRef . complete ( ) ; } } ) ) ; } param req private checkUrl ( req ) { const url = req . url . toLowerCase ( ) ; const found = this . _config . silentApis . find ( ( u ) => url . startsWith ( u ) ) ; return ! ! found ; } }