Is it good way to call subscribe inside subscribe?
The correct way is to compose the various observables in some manner then subscribe to the overall flow — how you compose them will depend on your exact requirements.
If you can do them all in parallel:
forkJoin(
this.service.service1(), this.service.service2(), this.service.service3()
).subscribe((res) => {
this.funcA(res[0], res[1], res[2]);
});
If each depends on the result of the previous, you can use mergeMap
(formerly known as flatMap
) or switchMap
:
this.service.service1().pipe(
mergeMap((res1) => this.service.service2(res1)),
mergeMap((res2) => this.service.service3(res2))
).subscribe((res3) => {
// Do something with res3.
});
... and so on. There are many operators to compose observables to cover lots of different scenarios.
You can use forkJoin
to combine the Observables
into a single value Observable
forkJoin(
this.service.service1(),
this.service.service2(),
this.service.service3()
).pipe(
map(([res1, res2, res3 ]) => {
this.funcA(res1, res2, res3);
})
If the calls can be resolved in parallel you could use forkJoin, like this:
joinedServiceCalls() {
return forkJoin(this.service1(), this.service2(), this.service3());
}
And then subscribe to that method. https://www.learnrxjs.io/operators/combination/forkjoin.html