Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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)?

like image 882
refactor Avatar asked Dec 28 '16 12:12

refactor


People also ask

How do I subscribe to multiple observables?

In our component, we use forkJoin to combine the Observables into a single value Observable. The forkJoin operator will subscribe to each Observable passed into it. Once it receives a value from all the Observables, it will emit a new value with the combined values of each Observable.

Can you subscribe to Observable multiple times?

It turns out that as the Observable is just a definition, let's remember that in a sense its something close to a function declaration, if we subscribe to it multiple times this means that each time a new HTTP request will be issued, one for each subscription.

Which is better promise or Observable?

The biggest difference is that Promises won't change their value once they have been fulfilled. They can only emit (reject, resolve) a single value. On the other hand, observables can emit multiple results. The subscriber will be receiving results until the observer is completed or unsubscribed from.


1 Answers

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;
    });
like image 162
Sergey Sokolov Avatar answered Sep 20 '22 07:09

Sergey Sokolov