How can I convert whatever Fetch API returns to RxJS Observable? Does RxJS.fromPromise help?
Approach: First make the necessary JavaScript file, HTML file and CSS file. Then store the API URL in a variable (here api_url). Define a async function (here getapi()) and pass api_url in that function. Define a constant response and store the fetched data by await fetch() method.
Summary. The Fetch API allows you to asynchronously request for a resource. Use the fetch() method to return a promise that resolves into a Response object. To get the actual data, you call one of the methods of the Response object e.g., text() or json() .
As fetch call returns yet another promise containing the response object, I'd go with creating your own observable:
import { Observable } from 'rxjs';
const data$ = Observable.create(observer => {
fetch('http://server.com')
.then(response => response.json()) // or text() or blob() etc.
.then(data => {
observer.next(data);
observer.complete();
})
.catch(err => observer.error(err));
});
data$.subscribe(data => /*do something with data*/);
check out this article
var result = Rx.Observable.fromPromise(fetch('http://myserver.com/'));
result.subscribe(x => console.log(x), e => console.error(e));
I'm using rxjs@6.
The operator that accepts observables(like flatMap
, switchMap
, etc...) can also accept promise.
it's very simple as follows.
somethingObservable.pipe(
flatMap(() => fetch('http://some.api.com/post/1')),
subscribe((response) => {
console.log(response);
}),
)
I am using rxjs 6.5.3. I am using below example to convert Fetch API response to RxJS Observable.
const { from } = rxjs;
const { map, switchMap } = rxjs.operators
const observable = from(fetch('data/user.json')).pipe(
switchMap(response => response.json())
)
observable.subscribe(function(result){
console.log('result', result);
});
You can also use fromFetch of rxjs. But fetch API are still experimental.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With