Subscribe to multiple Observables (e.g. then () chain in Promises)

My Angular 2 application has 2 methods ( GetCategories() and GetCartItems() ) in the service, and both of these methods return Observable s.

To call these two methods one after another from my component, I wrote the following 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)} }) }); } 

Essentially, calling GetCartItems() from GetCartItems() subscribe() the GetCategories() function, and I believe this is NOT the right approach. This is a kind of callback to hell.

Any idea on how to implement this better (e.g. then() chain in Promise s)?

+9
source share
2 answers

It seems that GetCartItems is independent of 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; }); 
+15
source

This is most often done with concat() , concatMap() or ultimately concatAll() depending on your account and what you need to call both services in order or not.

 function GetCategories() { return Observable.timer(1000).do(() => console.log('GetCategories()')); } function GetCartItems() { return Observable.timer(1000).do(() => console.log('GetCartItems()')); } console.log('start...'); GetCategories() .concatMap(() => GetCartItems()) .subscribe(() => console.log('done')); 

Sent to the console:

 start... GetCategories() GetCartItems() done 

Each element is delayed to show that they are called in order one after another.

If you do not need to keep the same order, you can use merge() or mergeMap() .

See the demo: https://jsbin.com/wawajob/1/edit

Please note that using zip() may have unwanted behavior. See https://github.com/Reactive-Extensions/RxJS/blob/master/doc/api/core/operators/zip.md

+7
source

Source: https://habr.com/ru/post/1013573/


All Articles