| 72 | */ |
| 73 | @Service() |
| 74 | export class FetchBackend implements HttpBackend { |
| 75 | // We use an arrow function to always reference the current global implementation of `fetch`. |
| 76 | // This is helpful for cases when the global `fetch` implementation is modified by external code, |
| 77 | // see https://github.com/angular/angular/issues/57527. |
| 78 | private readonly fetchImpl = |
| 79 | inject(FetchFactory, {optional: true})?.fetch ?? ((...args) => globalThis.fetch(...args)); |
| 80 | private readonly ngZone = inject(NgZone); |
| 81 | private readonly destroyRef = inject(DestroyRef); |
| 82 | private readonly maxResponseSize = inject(HTTP_FETCH_MAX_RESPONSE_SIZE); |
| 83 | |
| 84 | handle(request: HttpRequest<any>): Observable<HttpEvent<any>> { |
| 85 | return new Observable((observer) => { |
| 86 | if (this.destroyRef.destroyed) { |
| 87 | observer.unsubscribe(); |
| 88 | return undefined; |
| 89 | } |
| 90 | |
| 91 | const aborter = new AbortController(); |
| 92 | let done = false; |
| 93 | const wrappedObserver: Observer<HttpEvent<any>> = { |
| 94 | next: (val) => { |
| 95 | if (this.destroyRef.destroyed) { |
| 96 | return; |
| 97 | } |
| 98 | if (val.type === HttpEventType.Response) { |
| 99 | done = true; |
| 100 | } |
| 101 | observer.next(val); |
| 102 | }, |
| 103 | error: (err) => { |
| 104 | if (this.destroyRef.destroyed) { |
| 105 | return; |
| 106 | } |
| 107 | done = true; |
| 108 | observer.error(err); |
| 109 | }, |
| 110 | complete: () => { |
| 111 | if (this.destroyRef.destroyed) { |
| 112 | return; |
| 113 | } |
| 114 | done = true; |
| 115 | observer.complete(); |
| 116 | }, |
| 117 | }; |
| 118 | |
| 119 | const unregisterOnDestroy = this.destroyRef.onDestroy(() => { |
| 120 | // Call `unsubscribe()` instead of `complete()` or `error()` when the |
| 121 | // injector is destroyed. This aborts the in-flight `fetch` and releases |
| 122 | // observers without triggering `EmptyError` in `firstValueFrom`/`lastValueFrom` |
| 123 | // or unhandled rejections in unawaited async lifecycle hooks. |
| 124 | observer.unsubscribe(); |
| 125 | }); |
| 126 | |
| 127 | this.doRequest(request, aborter.signal, wrappedObserver).then(noop, (error) => |
| 128 | wrappedObserver.error(new HttpErrorResponse({error})), |
| 129 | ); |
| 130 | |
| 131 | let timeoutId: ReturnType<typeof setTimeout> | undefined; |