How to convert a Fetch API response to RxJS Observable

0 votes
Can you tell me with the help of cod and an example How to convert a Fetch API response to RxJS Observable?
Feb 26 in Node-js by Nidhi
• 10,860 points
47 views

1 answer to this question.

0 votes

To convert a Fetch API response into an RxJS Observable, use from or defer from rxjs.

Using from

import { from, Observable } from 'rxjs';

function fetchData(): Observable<Response> {

  return from(fetch('https://api.example.com/data'));

}

fetchData().subscribe(response => {

  console.log(response);

});

Using defer (Recommended for fresh execution on subscription)

import { defer, from, Observable } from 'rxjs';

function fetchData(): Observable<any> {

  return defer(() => from(fetch('https://api.example.com/data').then(res => res.json())));

}

fetchData().subscribe(data => {

  console.log(data);

});

answered Feb 26 by Kavya

Related Questions In Node-js

0 votes
1 answer

How to programmatically send a 404 response with Express/Node?

Hello @kartik, The method is: res.sendStatus(404); Express will send a ...READ MORE

answered Jul 16, 2020 in Node-js by Niroj
• 82,840 points
3,678 views
0 votes
1 answer

How to set the content-type of request header when using Fetch APi?

Hello @kartik, You need to create a fetch ...READ MORE

answered Oct 15, 2020 in Node-js by Niroj
• 82,840 points
8,229 views
0 votes
1 answer

How to install a previous exact version of a NPM package?

Hello @kartik, If you have to install an ...READ MORE

answered Jul 8, 2020 in Node-js by Niroj
• 82,840 points
2,898 views
0 votes
1 answer

How can I remove a port from url for node app using nginx

If you run your node server on ...READ MORE

answered Apr 10, 2018 in DevOps on Cloud by ajs3033
• 7,300 points
4,243 views
0 votes
4 answers

ReactJS vs Angular Comparison: Which is better?

Parameters React Angular Type React is a JavaScript library, and it ...READ MORE

answered Jan 7, 2021 in Events & Trending Topics by Focusteck
• 140 points
2,046 views
+2 votes
4 answers
0 votes
1 answer

How to schedule a google meet and get the meet link in NodeJs?

To create a Google Meet, you'll need ...READ MORE

answered May 27, 2022 in Node-js by Neha
• 9,020 points
4,082 views
0 votes
1 answer

How to open a popup when a button is clicked?

To open a popup (modal) when a ...READ MORE

answered Dec 31, 2024 in Node-js by Navya
89 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP