function stable
Uses the Fetch API to make an HTTP request.
fromFetch(input: string | Request, init: RequestInit & { selector: (response: Response) => ObservableInput<T>; }): Observable<T> input | string | Request | |
init | RequestInit & { selector: (response: Response) => ObservableInput<T>; } |
fromFetch(input: string | Request, init?: RequestInit): Observable<Response> input | string | Request | |
init | RequestInit | Optional. Default is |
Observable<Response>
WARNING Parts of the fetch API are still experimental. AbortController is required for this implementation to work and use cancellation appropriately.
Will automatically set up an internal AbortController in order to finalize the internal fetch when the subscription tears down.
If a signal is provided via the init argument, it will behave like it usually does with fetch. If the provided signal aborts, the error that fetch normally rejects with in that scenario will be emitted as an error from the observable.
Basic use
import { fromFetch } from 'rxjs/fetch';
import { switchMap, of, catchError } from 'rxjs';
const data$ = fromFetch('https://api.github.com/users?per_page=5').pipe(
switchMap(response => {
if (response.ok) {
// OK return data
return response.json();
} else {
// Server is returning a status requiring the client to try something else.
return of({ error: true, message: `Error ${ response.status }` });
}
}),
catchError(err => {
// Network or other error, handle appropriately
console.error(err);
return of({ error: true, message: err.message })
})
);
data$.subscribe({
next: result => console.log(result),
complete: () => console.log('done')
}); With HTTP responses that use chunked transfer encoding, the promise returned by fetch will resolve as soon as the response's headers are received.
That means the fromFetch observable will emit a Response - and will then complete - before the body is received. When one of the methods on the Response - like text() or json() - is called, the returned promise will not resolve until the entire body has been received. Unsubscribing from any observable that uses the promise as an observable input will not abort the request.
To facilitate aborting the retrieval of responses that use chunked transfer encoding, a selector can be specified via the init parameter:
import { of } from 'rxjs';
import { fromFetch } from 'rxjs/fetch';
const data$ = fromFetch('https://api.github.com/users?per_page=5', {
selector: response => response.json()
});
data$.subscribe({
next: result => console.log(result),
complete: () => console.log('done')
});
© 2015–2022 Google, Inc., Netflix, Inc., Microsoft Corp. and contributors.
Code licensed under an Apache-2.0 License. Documentation licensed under CC BY 4.0.
https://rxjs.dev/api/fetch/fromFetch