Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 Return Inner Observable of Nested Observables

I want to make multiple http call in Angular2 using observables. Each observable is dependent on the prior observable. If I want to return the inner observable, so I can subscribe to it in the parent component), how can this be done?

Here is what I've tried, but I wasn't able to subscribe to the observable in the parent component.

Child Component:

observablesFn(){
   observable1().subscribe(data1 => {
        observable2().subcribe(data2 => {
            //I want to return this observable (before subscription b/c I want to subscribe in the parent component)
            return observable3();
        })
   }
}
like image 926
PBandJen Avatar asked Feb 14 '17 23:02

PBandJen


1 Answers

Your question is hard to understand since you haven't given much context, but it sounds like you're looking to get the result of observable3() to return from observablesFn(). The existing return statement is returning from your nested inner anonymous function, not your outermost scope. I think you're looking to do something more along these lines.

observablesFn(){
  return observable1().map(data1 => {
    return observable2(data1).map(data2 => {
      return observable3(data1, data2);
    });
  });
}

This will return from observablesFn(), rather than its nested inner function.

It's necessary to use .map rather than .subscribe, since it returns an observable, rather than a subscription.

like image 98
Adam Avatar answered Nov 01 '22 15:11

Adam