1

I have a modal popup, which I am coding such that when an open() function is called, it returns an observable. Any subscriber will then get an object with a property indicating what button was pressed in the modal or whether it was closed, etc.

If a 'success' button is pressed, I want to make a http call, which in turn also returns an observable! How would I combine these two observables? In angular 1 with promises I can return promises from promises, so I would do something like

 var promise = modal.open()
                    .then(function(res) { 
                        if (res.success) {
                            return httpService.get(); // also returns a promise
                        }

                        return res;
                    });

how would I do something like this for observables?

Mark Rajcok
  • 362,217
  • 114
  • 495
  • 492
Umair
  • 3,063
  • 1
  • 29
  • 50

1 Answers1

1

You can leverage observable operators to build an asynchronous data flow. In you case, the switchMap operator:

var observable = modalObservable.switchMap(() => {
  return return httpService.get(); // also returns an observable
});

Be careful to import the operators you need since they aren't by default (see this question: Angular 2 HTTP GET with TypeScript error http.get(...).map is not a function in [null]):

import 'rxjs/add/operator/switchMap';

You could have a look at the following article and presentation for more details:

Community
  • 1
  • 1
Thierry Templier
  • 198,364
  • 44
  • 396
  • 360
  • Ok, but what about only returning the http observable conditionally? Based on a value from the modal observable subscription? – Umair Feb 25 '16 at 09:48
  • In fact, within the `switchMap`, you will receive this value as first parameter... So you can use it to create the new observable to return. – Thierry Templier Feb 25 '16 at 10:04
  • Ok thanks, but sorry one more question :) so with switchmap you can return a value (an object) or an observable? – Umair Feb 25 '16 at 10:47
  • If you want to return an object, use the `map` operator. With `switchMap`, you can return an observable that will take part of the processing chain... In your case, the `httpService.get()` will be executed and the response will be then handled in the asynchronous processing chain (for example received in a `subscribe` method). – Thierry Templier Feb 25 '16 at 10:51
  • Ok well that's the problem! I need to combine the two like in my promise example. Can I do something like `modalObservable.switchMap((r) => { if (r.success) { return httpService.get(); } else { Observable.from(r); } });` – Umair Feb 25 '16 at 13:04
  • Yes but don't forget the return within the `else` ;-) – Thierry Templier Feb 25 '16 at 13:06
  • observable.from or observable.of ? – user292701 Nov 01 '17 at 15:42