Search code examples
angularnestedobservablesubscription

Angular5 nested observable-subscriptions to a single observable


I have the following code in the service layer and I have two questions:

return this.equipmentService.getEquipment(this.id) //returns subscription
  .subscribe((equipment : Equipment) =>
  {
    this.getEquipmentTags(); //returns subscription
    this.getPredictions(); //returns subscription
  });
});
  1. In the code, I have subscribed to equipmentService.getEquipment observable and now it returns Subscription object - how can I make it an observable object again so it can be handled again in the business layer for example
  2. How can I be aware that all inner observables finished their tasks and trigger an event (or call a method or create another observable that I can subscribe later in the code)

Solution

  • Do not fire the subscription too early, as @igor point out and you (this.equipmentService.getEquipment(this.id) do not returns a subscription, it returns an Observable, because in other way you cannot subscribe to it), use concatMap (and pipeable operators) to get chained you Observables.

    getChainedObservables() {
      return this.equipmentService.getEquipment(this.id)
        .pipe(
          concatMap((equipment : Equipment) => this.getEquipmentTags()),
          concatMap(() => this.getPredictions())
        );
    }
    

    then call it,

    this.getChainedObservables().subscribe(console.log);