Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to properly make a GET call in React returning an observable (resembling the method in Angular and not using promises)?

In Angular, I usually subscribe to a client providing me with an observable of a GET call as Google dictates.

httpClient.get<Data>("http://blah")
  .subscribe(
    result => { ... },
    error => { ... },
    () => { ... }
  );

I'm trying to learn React and perform corresponding operation. The info I find is about using promises, which I prefer not to go with. Of course, the services of Angular lack their counterpart in React as such but since rxjs is an independent library, I feel that it makes sense to try to incorporate it into a React project.

How do I do that and what am I missing in my googling looking for it?

I'm also humbly considering the alternative that, since React is based on a different paradigm (i.e. stores instead of services), I might be barking up a very awkward tree.

like image 386
DonkeyBanana Avatar asked Jan 28 '23 09:01

DonkeyBanana


2 Answers

The reason why Angular Http benefits from observables is that some parts of Angular use observables, so they can be efficiently composed, e.g. reactive form observable can be throttled and piped to Http. It's not uncommon that Http observable is converted toPromise(), just because it's complete observable with single value and it can benefit from async..await when being a promise.

Unless React project heavily uses observables (for instance, with redux-observable), there will be much less benefits than in Angular.

As another answer mentions, there's built-in HTTP request API in RxJS, rxjs/ajax. It's a wrapper around XMLHttpRequest, this means that it provides cancellable requests, as opposed to some promise-based APIs, notably Fetch. It's very simplistic and lacks features that may be expected from Http alternative - interceptors, etc.

Axios can be generally recommended as framework-agnostic, full-featured promise-based alternative to Angular Http. It was modeled after AngularJS $http. A promise from it can be converted to an observable but additional measures should be taken to make a request cancellable.

TL;DR: the biggest selling of Http is that its observables can be composed with other observables. If there are none, the benefits are much less obvious. Promises can benefit from async..await syntactic sugar while observables have to be converted to promises any way to benefit from it.

like image 142
Estus Flask Avatar answered Jan 29 '23 22:01

Estus Flask


Just instead of Angular's httpClient you can use build-in RxJS ajax methods:

import { ajax } from 'rxjs/ajax';

ajax.get('https://httpbin.org/get')
  .subscribe(console.log);

Live demo: https://stackblitz.com/edit/rxjs6-demo-nsgdri?file=index.ts

like image 36
martin Avatar answered Jan 29 '23 22:01

martin