简体   繁体   English

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

[英]Angular2 nested observable cart total but value return undefined

I want to calculate the total amount of the shopping basket. 我想计算购物篮的总金额。 I have ShoppingCartItem and Product tables. 我有ShoppingCartItem产品表。 I have bellow code 我有下面的代码

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

Returning qty value works but total value returning undefined 返回数量价值的作品,但价值返回undefined

This Plunker 柱塞

Let me know if this works, since I do not have the whole of your source code and API data. 让我知道这是否可行,因为我没有您的全部源代码和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
}

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

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