2016-11-24 63 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)。你能幫我嗎? –