How to convert API Fetch response to RxJS Observable?

How can I convert all returned Fetch APIs to RxJS Observable ? Does RxJS.fromPromise help?

+10


source to share


6 answers


check this article



var result = Rx.Observable.fromPromise(fetch('http://myserver.com/'));
result.subscribe(x => console.log(x), e => console.error(e));

      

+11


source


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*/);
      

Run codeHide result


+25


source


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);
    }),
)

      

+5


source


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 )

+2


source


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)

      

}

+2


source


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.

+1


source







All Articles