我的 Angular 2 应用程序有 2 种方法(GetCategories()
and GetCartItems()
) 在服务中,这两个方法都返回Observable
s.
为了从我的组件中依次调用这两个方法,我编写了以下代码:
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)}
})
});
}
基本上,调用GetCartItems()
从内部subscribe()
of GetCategories()
,我觉得这不是正确的方法。这是一种回调地狱。
关于如何以更好的方式实现这一点的任何想法(例如链接then()
in Promise
s)?
好像GetCartItems
不依赖于GetCategories
。然后你可以使用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;
});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)