How to convert a Fetch API response to RxJS Observable?
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*/);
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);
}),
)
check out this article
var result = Rx.Observable.fromPromise(fetch('http://myserver.com/'));
result.subscribe(x => console.log(x), e => console.error(e));