Angular2 Returning an internal observable from nested observations

I want to make some http calls in Angular2 using observables. Each observable depends on the previous 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 tried, but I could not subscribe to the observable in the parent component.

Children's 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(); }) } } 
+5
source share
1 answer

It's hard to understand your question since you did not get much context, but it looks like you want to return the result of observable3() to return from observablesFn() . The existing return returned from your nested internal anonymous function, not from your outer scope. I think you want to do something else in this direction.

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

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

You must use .map , not .subscribe , as it returns an observable, not a subscription.

+7
source

Source: https://habr.com/ru/post/1264216/


All Articles