|
6 | 6 | * found in the LICENSE file at https://angular.io/license
|
7 | 7 | */
|
8 | 8 |
|
9 |
| -import {Inject, ModuleWithProviders, NgModule, Optional} from '@angular/core'; |
| 9 | +import {Injectable, Injector, ModuleWithProviders, NgModule, Optional} from '@angular/core'; |
| 10 | +import {Observable} from 'rxjs/Observable'; |
10 | 11 |
|
11 | 12 | import {HttpBackend, HttpHandler} from './backend';
|
12 | 13 | import {HttpClient} from './client';
|
13 | 14 | import {HTTP_INTERCEPTORS, HttpInterceptor, HttpInterceptorHandler, NoopInterceptor} from './interceptor';
|
14 | 15 | import {JsonpCallbackContext, JsonpClientBackend, JsonpInterceptor} from './jsonp';
|
| 16 | +import {HttpRequest} from './request'; |
| 17 | +import {HttpEvent} from './response'; |
15 | 18 | import {BrowserXhr, HttpXhrBackend, XhrFactory} from './xhr';
|
16 | 19 | import {HttpXsrfCookieExtractor, HttpXsrfInterceptor, HttpXsrfTokenExtractor, XSRF_COOKIE_NAME, XSRF_HEADER_NAME} from './xsrf';
|
17 | 20 |
|
| 21 | +/** |
| 22 | + * An `HttpHandler` that applies a bunch of `HttpInterceptor`s |
| 23 | + * to a request before passing it to the given `HttpBackend`. |
| 24 | + * |
| 25 | + * The interceptors are loaded lazily from the injector, to allow |
| 26 | + * interceptors to themselves inject classes depending indirectly |
| 27 | + * on `HttpInterceptingHandler` itself. |
| 28 | + */ |
| 29 | +@Injectable() |
| 30 | +export class HttpInterceptingHandler implements HttpHandler { |
| 31 | + private chain: HttpHandler|null = null; |
18 | 32 |
|
| 33 | + constructor(private backend: HttpBackend, private injector: Injector) {} |
| 34 | + |
| 35 | + handle(req: HttpRequest<any>): Observable<HttpEvent<any>> { |
| 36 | + if (this.chain === null) { |
| 37 | + const interceptors = this.injector.get(HTTP_INTERCEPTORS, []); |
| 38 | + this.chain = interceptors.reduceRight( |
| 39 | + (next, interceptor) => new HttpInterceptorHandler(next, interceptor), this.backend); |
| 40 | + } |
| 41 | + return this.chain.handle(req); |
| 42 | + } |
| 43 | +} |
19 | 44 |
|
20 | 45 | /**
|
21 | 46 | * Constructs an `HttpHandler` that applies a bunch of `HttpInterceptor`s
|
@@ -118,13 +143,7 @@ export class HttpClientXsrfModule {
|
118 | 143 | ],
|
119 | 144 | providers: [
|
120 | 145 | HttpClient,
|
121 |
| - // HttpHandler is the backend + interceptors and is constructed |
122 |
| - // using the interceptingHandler factory function. |
123 |
| - { |
124 |
| - provide: HttpHandler, |
125 |
| - useFactory: interceptingHandler, |
126 |
| - deps: [HttpBackend, [new Optional(), new Inject(HTTP_INTERCEPTORS)]], |
127 |
| - }, |
| 146 | + {provide: HttpHandler, useClass: HttpInterceptingHandler}, |
128 | 147 | HttpXhrBackend,
|
129 | 148 | {provide: HttpBackend, useExisting: HttpXhrBackend},
|
130 | 149 | BrowserXhr,
|
|
0 commit comments