Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a Fetch API response to RxJS Observable?

How can I convert whatever Fetch API returns to RxJS Observable? Does RxJS.fromPromise help?

like image 795
wonderful world Avatar asked Jul 03 '17 02:07

wonderful world


People also ask

How do I get fetch from API response?

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.

Can we fetch data from API?

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() .


Video Answer


4 Answers

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*/);
like image 129
wawka Avatar answered Oct 29 '22 03:10

wawka


check out this article

var result = Rx.Observable.fromPromise(fetch('http://myserver.com/'));
result.subscribe(x => console.log(x), e => console.error(e));
like image 43
kit Avatar answered Oct 29 '22 03:10

kit


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);
    }),
)
like image 25
Shota Tamura Avatar answered Oct 29 '22 03:10

Shota Tamura


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.

like image 33
Kuldeep Semwal Avatar answered Oct 29 '22 03:10

Kuldeep Semwal