Handling HTTP Request using RxJs in Angular

Abhishek Ankush
Apr 2 · 5 min read

Handling HTTP request in an Angular application is a crucial part. In this article we will go through below methods from RxJs to handle HTTP requests.

  1. map → applies the function supplied to each value of input observable and emits the resulting value as observable.
  2. mergeMap or flatMap → allows us to flatten multiple separate subscribed Observable into a single cohesive stream, which we can use to control events coming from user input and from server responses.
  3. switchMap → Projects each source value to an Observable which is merged in the output Observable, emitting values only from the most recently projected Observable.
  4. forkJoin → Accepts an Array of ObservableInput or a dictionary Object of ObservableInput and returns an Observable that emits either an array of values in the exact same order as the passed array, or a dictionary of values in the same shape as the passed dictionary.

map

Use case: One use case could be we want to convert all observables into observables of JSON objects.

As shown in Example when we want to return the result from service as json so map function is applying the logic on the input observable and returns the json as observable.

Pros: As it helps in applying project function on the input observable and emits them as observable, it helps in modifying the response data in desired manner.

mergeMap or flatMap

Use Case: When we want to access the value of one subscribed observable into another, we can use the mergeMap to pass it and get the a single cohesive stream we can use to control events.

Example: Say you want to do call 2 HTTP request sequentially where we are passing value of one to another. Lets try to use mergeMap for the same.

Pros: We can Make HTTP request sequentially dynamically.

Cons: It doesn't cancels the previously called observable subscription which could cause the mix-up of the responses.

Note that flatMap flattens a stream of (i.e of ) to a stream of emitted values (a simple ), by emitting on the "trunk" stream everything that will be emitted on "branch" streams.

switchMap

switchMap is very similar to flatMap, but with a very important distinction. Any events to be merged into the trunk stream are ignored if a new event comes in.

Use Case: Let’s say we wanted to implement a server based search feature in which every keypress in a text field will automatically perform a search and update the page with the results. How would this look? Well we would have an subscribed to events coming from an input field, and on every change of input we want to perform some HTTP request, which is also an we subscribe to. What we end up with is an of an .

Say we use flatMap for this. Service will look like below

Service

OK, let’s take a look at the component that will be using this service.

We have one issue here if the server, for some reason, takes a very long time to respond to a particular query. If we use flatMap, we run the risk of getting results back from the server in the wrong order. Let's illustrate this with an example.

We can solve this using switchMap. Updated component code for swithMap

This implementation of incremental search with switchMap is more robust than the one we saw on the previous page with flatMap as the old trunk of Tabl is ignored when the call is made with Table so that user will always see the last thing user typed. Thanks to this, we can guarantee a great user experience regardless of how the server responds.

Pros: As the old trunk is ignored we have a great user experience regardless of the server response.

Cons: As the old trunk is ignored in case of multiple parallel calls will overwritten with the last one.

forkJoin

forkJoin help us to do multiple http calls in parallel and waits for them to resolve.

forkJoin will wait for all the request to resolve and group all the observables returned by each HTTP call into a single observable array and finally returns the same.

In example above we have done 2 HTTP calls, the same way can be used for desired number of calls.

We can subscribe the response as shown in the above example.

Pros: With forkJoin we can join observables from different HTTP calls and respond as one observable array.

Cons: If any of the inner observables supplied to forkJoin error you will lose the value of any other observables that would or have already completed. We can avoid this with catching error properly in inner observable.

👏

Frontend Weekly

It's really hard to keep up with all the front-end…

Frontend Weekly

It's really hard to keep up with all the front-end development news out there. Let us help you. We hand-pick interesting articles related to front-end development. You can also subscribe to our weekly newsletter at http://frontendweekly.co

Abhishek Ankush

Written by

A fullstack software developer since 2012. I am a programming addict. I love learning and sharing knowledge.

Frontend Weekly

It's really hard to keep up with all the front-end development news out there. Let us help you. We hand-pick interesting articles related to front-end development. You can also subscribe to our weekly newsletter at http://frontendweekly.co

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store