Subscribe to multiple Observables (like chaining then() in Promises)

refactor picture refactor · Dec 28, 2016 · Viewed 15.6k times · Source

My Angular 2 application has 2 methods (GetCategories() and GetCartItems()) in a service , and both of these methods return Observables.

In order to invoke these two methods one after another from my component, I have written below code:

 ngOnInit() 
{
   this.appService.GetCategories().subscribe( (data) => {
       this.appService.categories = data;


       this.appService.GetCartItems().subscribe( {
                                                    next: (data) => { this.appService.cart = data},
                                                    error: (err) => { this.toaster.error('cart==>' + err)}

                                                })

   });       
}

Basically, calling GetCartItems() from within subscribe() of GetCategories(), and I feel this is NOT the right approach. This is kind of callback hell.

Any idea on how to implement this in a better way (like chaining then() in Promises)?

Answer

Sergey Sokolov picture Sergey Sokolov · Dec 28, 2016

Looks like GetCartItems doens't depend on GetCategories. Then you can use zip:

Observable
    .zip(
        this.appService.GetCategories()
        this.appService.GetCartItems()
    )
    .catch(err => this.toaster.error(err))
    .subscribe(([categories, cartItems]) => {
        this.appService.categories = categories;
        this.appService.cart = cartItems;
    });