简体   繁体   English

将2个可观察对象合并/合并为一个

[英]Combining / Merging 2 observables into one

Im trying to combine 2 Observables. 我正在尝试结合2个Observables。 The first observable Holds a ShoppingCart class and the second holds a list of ShoppingItems . 第一次观察到一举行ShoppingCart类;第二个保存列表ShoppingItems I want to map the observable with shopping cart items ( Observable<ShoppingItems ) to the instance variable within the ShoppingCart class called shoppingList$ . 我想将带有购物车项目的Observable<ShoppingItemsObservable<ShoppingItems )映射到ShoppingCart类中名为shoppingList$的实例变量。

Observable 1: Observable<ShoppingCart> 可观察1: Observable<ShoppingCart>

Here's a snippet of the shopping cart class. 这是购物车类的摘录。

export class ShoppingCart {
private shoppingList$: Observable<ShoppingItems> 
private selectedIndex: number;
... etc
}

Observable 2: Observable<ShoppingItems[]> private observable: Observable 可观察2: Observable<ShoppingItems[]>私有可观察:可观察

Here is the function I am using. 这是我正在使用的功能。

retrieveShoppingCartComplete(shoppingCartId: string): Observable<ShoppingCart> {

/**Returns the requested shopping cart, with the Ids of the shopping items in an array called shoppingCart.ShoppingItems*/
    let shoppingCart$ = this.retrieveShoppingCart_AsEntity(shoppingCartId); 


/** returns an Observable<ShoppingItems[]> of the requested ShoppingItems as entitys*/
    let shoppingItems$ = shoppingCart$.map(shoppingCart => this.leS.retrieveShoppingItemsComplete(shoppingCart.ShoppingItemsIds))

   return shoppingCart$.combineAll(shoppingItems$);
}

However the method above returns an Observable<[ShoppingCart | ShoppingItems[]]> 但是,上述方法返回Observable<[ShoppingCart | ShoppingItems[]]> Observable<[ShoppingCart | ShoppingItems[]]> not an Observable<ShoppingCart> with the Observable<ShoppingItems> array assigned to the shoppingList$ instance variable in the ShoppingCart Class Observable<[ShoppingCart | ShoppingItems[]]>不是一个Observable<ShoppingCart>与所述Observable<ShoppingItems>分配给阵列shoppingList$在该实例变量ShoppingCart

I think combineAll is not what you need here. 我认为combineAll不是您所需要的。 I'd use flatMap to chain two service calls like this: 我将使用flatMap链接两个服务调用,如下所示:

retrieveShoppingCartComplete(shoppingCartId: string): Observable<ShoppingCart> {
    return this.retrieveShoppingCart_AsEntity(shoppingCartId)
        .flatMap(shoppingCart => {
            shoppingCart.shoppingList$ = this.leS.retrieveShoppingItemsComplete(shoppingCart.ShoppingItemsIds)
        })
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM