简体   繁体   中英

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM