2016-11-24 55 views
0

我想计算购物篮的总金额。我有ShoppingCartItem产品表。我有娄代码Angular2嵌套可观察车总数,但返回值未定义

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

+0

'total'不能因为它的默认值是数字0 –

+0

cartItem.product.price回报不确定,因为总价值回归未定义或错误 –

+0

可能的复制[我要计算的总和是'undefined'购物车在Firebase与Angularfire2](http://stackoverflow.com/questions/40833704/i-want-to-calculate-the-sum-of-the-shoppingcart-at-firebase-with-angularfire2) – STEEL

回答

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 
} 
+0

返回这样的错误:类型'Observable '上不存在属性'qty'。这个链接的更详细的描述[链接](http://stackoverflow.com/questions/40833704/i-want-to-calculate-the-sum-of-the-shoppingcart-at-firebase-with-angularfire2)。我想你会给出一个更好的主意。感谢您的关注。 –

+0

告诉你关于你的代码的第一件事,数据在你的API数据中是分开的,这很好。但是获得产品价格的前端逻辑并不好。 可以请你分享这个[plunker]模拟数据 – STEEL

+0

(http://plnkr.co/edit/cWdXRGNk08NDtArDj10O?p=preview)。你能帮我吗? –