8
votes

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();
        })
   }
}
1

1 Answers

8
votes

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.