问题描述
我的Angular 2应用程序在服务中有2个方法(GetCategories()
和GetCartItems()
),并且这两个方法都返回Observable
s.
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)}
})
});
}
基本上,从GetCategories()
的subscribe()
内部调用GetCartItems()
,我认为这不是正确的方法.这是一种回调地狱.
Basically, calling GetCartItems()
from within subscribe()
of GetCategories()
, and I feel this is NOT the right approach. This is kind of callback hell.
关于如何以更好的方式实现这一点的任何想法(例如在Promise
s中链接then()
)?
Any idea on how to implement this in a better way (like chaining then()
in Promise
s)?
推荐答案
类似于GetCartItems
的外观并不依赖GetCategories
.然后,您可以使用 zip :
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;
});
这篇关于订阅多个Observable(例如在Promises中链接then())的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!