// https://github.com/52North/helgoland-toolbox/blob/495f75cadcc3e7232206db1cd5dd8bbf3a172c4b/libs/core/src/lib/dataset-api/http.service.ts#L37 import { Injectable } from '@angular/core'; import { HttpClient, HttpEvent, HttpHandler, HttpRequest } from '@angular/common/http'; import { Inject, InjectionToken, Optional } from '@angular/core'; import { Observable } from 'rxjs'; import { HttpRequestOptions } from '../../shared/models/http-requests'; export const HTTP_SERVICE_INTERCEPTORS = new InjectionToken('HTTP_SERVICE_INTERCEPTORS'); export interface HttpServiceHandler { handle(req: HttpRequest, options: Partial): Observable>; } export interface HttpServiceInterceptor { intercept(req: HttpRequest, options: Partial, next: HttpServiceHandler): Observable>; } @Injectable() export class HttpService { private handler: HttpServiceHandler; constructor( protected httpHandler: HttpHandler, @Optional() @Inject(HTTP_SERVICE_INTERCEPTORS) interceptors: HttpServiceInterceptor[] | null ) { let handler: HttpServiceHandler = { handle: (req, options) => httpHandler.handle(req) }; if (interceptors) { handler = interceptors.reduceRight((next, interceptor) => ({ handle: (req, options) => interceptor.intercept(req, options, next) }), handler); } this.handler = handler; } public client(options: HttpRequestOptions = {}): HttpClient { return new HttpClient({ handle: (req) => this.handler.handle(req, options) }); } }