My Angular 2 application has 2 methods (GetCategories()
and GetCartItems()
) in a service , and both of these methods return Observable
s.
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 Promise
s)?
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.
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.
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.
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;
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With