订阅多个 Observables(比如在 Promises 中链接 then()) [英] Subscribe to multiple Observables (like chaining then() in Promises)

查看:21
本文介绍了订阅多个 Observables(比如在 Promises 中链接 then())的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的 Angular 2 应用程序在一个服务中有 2 个方法(GetCategories()GetCartItems()),并且这两个方法都返回 Observables.

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

                                                })

   });       
}

基本上,从 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.

关于如何以更好的方式实现这一点的任何想法(比如在 Promises 中链接 then())?

Any idea on how to implement this in a better way (like chaining then() in Promises)?

推荐答案

看起来 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;
    });

这篇关于订阅多个 Observables(比如在 Promises 中链接 then())的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆