import { Inject , Injectable , InjectionToken , Injector , Optional } from '@angular/core' ; import { HttpClient , HttpEvent , HttpInterceptor , HttpHandler , HttpRequest } from '@angular/common/http' ; import { Observable } from 'rxjs' ; import { ErrorHandlerInterceptor } from './error-handler.interceptor' ; import { CacheInterceptor } from './cache.interceptor' ; import { ApiPrefixInterceptor } from './api-prefix.interceptor' ; declare module '@angular/common/http/src/client' { export interface HttpClient { param { boolean } forceUpdate return { HttpClient } cache ( forceUpdate ? ) : HttpClient ; return { HttpClient } skipErrorHandler ( ) : HttpClient ; return { HttpClient } disableApiPrefix ( ) : HttpClient ; } } class HttpInterceptorHandler implements HttpHandler { constructor ( private next , private interceptor ) { } handle ( request ) { return this . interceptor . intercept ( request , this . next ) ; } } /**
 * Allows to override default dynamic interceptors that can be disabled with the HttpService extension.
 * Except for very specific needs, you should better configure these interceptors directly in the constructor below
 * for better readability.
 *
 * For static interceptors that should always be enabled (like ApiPrefixInterceptor), use the standard
 * HTTP_INTERCEPTORS token.
 */ export const HTTP_DYNAMIC_INTERCEPTORS = new InjectionToken < HttpInterceptor > ( 'HTTP_DYNAMIC_INTERCEPTORS' ) ; /**
 * Extends HttpClient with per request configuration using dynamic interceptors.
 */ @ Injectable ( ) export class HttpService extends HttpClient { constructor ( private httpHandler , private injector , @ Optional ( ) @ Inject ( HTTP_DYNAMIC_INTERCEPTORS ) private interceptors = [ ] ) { super ( httpHandler ) ; if ( ! this . interceptors ) { this . interceptors = [ this . injector . get ( ApiPrefixInterceptor ) , this . injector . get ( ErrorHandlerInterceptor ) ] ; } } cache ( forceUpdate ? ) { const cacheInterceptor = this . injector . get ( CacheInterceptor ) . configure ( { update : forceUpdate } ) ; return this . addInterceptor ( cacheInterceptor ) ; } skipErrorHandler ( ) { return this . removeInterceptor ( ErrorHandlerInterceptor ) ; } disableApiPrefix ( ) { return this . removeInterceptor ( ApiPrefixInterceptor ) ; } request ( method ? , url ? , options ? ) { const handler = this . interceptors . reduceRight ( ( next , interceptor ) => new HttpInterceptorHandler ( next , interceptor ) , this . httpHandler ) ; return new HttpClient ( handler ) . request ( method , url , options ) ; } private removeInterceptor ( interceptorType ) { return new HttpService ( this . httpHandler , this . injector , this . interceptors . filter ( i => ! ( i instanceof interceptorType ) ) ) ; } private addInterceptor ( interceptor ) { return new HttpService ( this . httpHandler , this . injector , this . interceptors . concat ( [ interceptor ] ) ) ; } }