Angular2嵌套可观察购物车总数但值返回未定义

时间:2016-11-24 15:10:34

标签: angular angularfire2

我想计算购物篮的总金额。我有 ShoppingCartItem 产品表。我有以下代码

cartTotals(qty = 0, total = 0) {
return this.af.database.list('ShoppingCartItem')
  .map(carts => {
    carts.map(cart => {
        this.af.database.object(`Product/${cart.productId}`)
        .subscribe(d => {
            cart.product = d;
        });
      return cart;
    });
    carts.forEach(cartItem => {
        qty += cartItem.quantity;
        total += cartItem.quantity * cartItem.product.price;
        // console.log(cartItem);
    });
    return {qty, total};
  });
}

返回数量值有效但值返回undefined

Plunker

1 个答案:

答案 0 :(得分:0)

如果有效,请告诉我,因为我没有完整的源代码和API数据。

cartTotals(qty = 0, total = 0) {
  return this.af.database.list('ShoppingCartItem')
   .map(carts => carts.map(cart => cart.product = this.findProductFromCartId(cart.productId)))
   .map(carts => carts.map(cartItem => {
        cartItem.qty = cartItem.quantity + qty;
        cartItem.total = (cartItem.quantity * cartItem.product.price) + total;
        return cartItem;
    });
}

findProductFromCartId(id) {
    return this.af.database.object(`Product/${id}`)
        .flatMap(product => Observable.combineLatest(product));//add this onlyIF its returned FirebaseObservable Object
}