Last active
October 1, 2018 10:00
-
-
Save wKoza/4fe567b062275a3fde7ad12e72196ea3 to your computer and use it in GitHub Desktop.
This file contains 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 {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