Skip to content

Instantly share code, notes, and snippets.

@wKoza
Last active October 1, 2018 10:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wKoza/4fe567b062275a3fde7ad12e72196ea3 to your computer and use it in GitHub Desktop.
Save wKoza/4fe567b062275a3fde7ad12e72196ea3 to your computer and use it in GitHub Desktop.
import {InjectionToken, Injector} from '@angular/core';
import {HttpBackend, HttpEvent, HttpInterceptor, HttpReques, HttpHandler, HttpRequest} from '@angular/common/http';
import { Observable } from 'rxjs';
/**
* `HttpHandler` which applies an `HttpInterceptor` to an `HttpRequest`.
*/
export class MyHttpInterceptorHandler implements HttpHandler {
constructor(private next: HttpHandler, private interceptor: HttpInterceptor) {}
handle(req: HttpRequest<any>): Observable<HttpEvent<any>> {
return this.interceptor.intercept(req, this.next);
}
}
export class MyHandlerService implements HttpHandler {
private chain: HttpHandler | null = null;
constructor(private backend: HttpBackend, private injector: Injector, private interceptors: InjectionToken<HttpInterceptor[]>) { }
handle(req: HttpRequest<any>): Observable<HttpEvent<any>> {
if (this.chain === null) {
const interceptors = this.injector.get(this.interceptors, []);
this.chain = interceptors.reduceRight(
(next, interceptor) => new MyHttpInterceptorHandler(next, interceptor), this.backend);
}
return this.chain.handle(req);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment