How to convert API Fetch response to RxJS Observable?
How can I convert all returned Fetch APIs to RxJS Observable ? Does RxJS.fromPromise help?
source to share
Since the fetch call returns another promise containing the response object, I would go for 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*/);
source to share
I am using rxjs @ 6.
The operator, which receives the observed (e.g. flatMap
, switchMap
etc.), may also take promise. it is very simple as follows.
somethingObservable.pipe(
flatMap(() => fetch('http://some.api.com/post/1')),
subscribe((response) => {
console.log(response);
}),
)
source to share
There is libary rxjs-fetch , but I would suggest not using it and instead write:
const getData = (url, params) => {
return fetch(url, params).then(r => {
return r.ok ? r.text() : Promise.reject(`${r.statusText} ${r.status}`)
})
}
const getDataObserver = (url, params) => Rx.Observable.fromPromise(getData())
(in NodeJS you need node-fetch )
source to share
Using rxjs 6.4 you can use the from operator
See this link: https://www.learnrxjs.io/operators/creation/from.html
Example in TS:
public getModelDetails(): Observable<YourType> {
const apiCall = fetch('yourURL/modelDetails')
.then(response => response.json())
.then(responseJson => {
return responseJson as YourType
})
return from(apiCall)
}
source to share
I am using rxjs 6.5.3. I am using the example below to convert the 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 from rxjs. But the get APIs are still experimental.
source to share