| 100 | } |
| 101 | |
| 102 | handle(initialRequest: HttpRequest<any>): Observable<HttpEvent<any>> { |
| 103 | if (this.chain === null) { |
| 104 | const parentHandler = this.injector.get(HttpHandler, null, {skipSelf: true}); |
| 105 | const isDelegating = parentHandler !== null && this.backend === parentHandler; |
| 106 | const rootInterceptorFns = this.injector.get( |
| 107 | HTTP_ROOT_INTERCEPTOR_FNS, |
| 108 | [], |
| 109 | isDelegating ? {self: true} : undefined, |
| 110 | ); |
| 111 | const dedupedInterceptorFns = Array.from( |
| 112 | new Set([...this.injector.get(HTTP_INTERCEPTOR_FNS), ...rootInterceptorFns]), |
| 113 | ); |
| 114 | |
| 115 | // Note: interceptors are wrapped right-to-left so that final execution order is |
| 116 | // left-to-right. That is, if `dedupedInterceptorFns` is the array `[a, b, c]`, we want to |
| 117 | // produce a chain that is conceptually `c(b(a(end)))`, which we build from the inside |
| 118 | // out. |
| 119 | this.chain = dedupedInterceptorFns.reduceRight( |
| 120 | (nextSequencedFn, interceptorFn) => |
| 121 | chainedInterceptorFn(nextSequencedFn, interceptorFn, this.injector), |
| 122 | interceptorChainEndFn as ChainedInterceptorFn<unknown>, |
| 123 | ); |
| 124 | } |
| 125 | |
| 126 | const chain = this.chain; |
| 127 | if (this.contributeToStability && !this.destroyRef.destroyed) { |
| 128 | const removeTask = this.pendingTasks.add(); |
| 129 | const unregisterDestroy = this.destroyRef.onDestroy(removeTask); |
| 130 | const cleanup = () => { |
| 131 | unregisterDestroy(); |
| 132 | removeTask(); |
| 133 | }; |
| 134 | try { |
| 135 | return untracked(() => |
| 136 | chain(initialRequest, (downstreamRequest) => this.backend.handle(downstreamRequest)), |
| 137 | ).pipe(finalize(cleanup)); |
| 138 | } catch (error) { |
| 139 | cleanup(); |
| 140 | throw error; |
| 141 | } |
| 142 | } else { |
| 143 | return untracked(() => |
| 144 | chain(initialRequest, (downstreamRequest) => this.backend.handle(downstreamRequest)), |
| 145 | ); |
| 146 | } |
| 147 | } |
| 148 | } |
| 149 | |
| 150 | /** |