Returning Data from a Nested Subscribe in Angular & RxJs

RxJs is a really powerful library for doing reactive programming and working with data. Like any powerful library though we run into issues that might make us scratch our head if we haven’t seen before.

Say for example have a method in a service or controller in Angular that needs to return some data from an inner or nested subscribe.

If we try and do it like this, the method will try and return a subscription to the observable when we’re trying to return an observable with real data.

There are a few different ways to fix this, but I will present two options.

The first option is to use where we create a new observable that can be subscribed to and pipe a value to it.

In the getData method, we create the observable with a function that takes the new observable as an argument and now we’re able to subscribe to the two other observables to get the data we need and still return an observable from inside a parent subscribe.

Code Sandbox

The next method requires less code and is a bit simpler. We use the powerful switchMap operator to return a different observable.

Pretend you're a valet and you need to get a car that is blocked in by one or more cars. You start by calling the first car that is blocking, then once you’re down to the car that has been requested, you use switchMap to get just that car and that’s the actual car that is being presented.

It’s the same thing with observables, we have a setup task that we subscribe to, but that’s not the result we want. We use a switchMap to switch out the observable that we actually need.

We can then operate further on the observable returned from switchMap and use the map function to return only the data we need.

In the example above, we’re asking the getSetupData method to pipe its returned value to getUsefulData via switchMap which will give us the observable returned from getUsefulData.

Since we only need a single string from usefulData object, we use map to return just the single datapoint.

Code Sandbox

Developer at Knowledge Anywhere

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