我想用 Angularfire2 计算 Firebase 上 ShoppingCart 的总和 [英] I want to calculate the sum of the ShoppingCart at Firebase with Angularfire2
问题描述
我正在构建一个使用 Angular2、Firebase 和 AngularFire2 的实验性应用程序.这是我的数据的样子:
I'm building an experimental application that uses Angular2, Firebase and AngularFire2. This is what my data looks like:
{
"ShoppingCartItem":
{
"item1":{
"quantity": 2,
"productId": "abc"
},
"item2":{
"quantity": 1,
"productId": "bcd"
}
}
"Product"
{
"abc":{
"name": "product1",
"price": 5
},
"bcd":{
"name": "product2",
"price": 6
}
}
}
下面是我的cart.ts
Below are my cart.ts
this.items = this.af.database.list('ShoppingCartItem')
.map(carts => {
return carts.map(item => {
item.product = this.af.database.object(`Product/${item.productId}`);
return item;
});
});
下面是我的cart.html
Below are my cart.html
<table>
<tbody>
<tr *ngFor="let item of (items | async)">
<td>{{(item.product | async)?.name}}</td>
<td><input type="text" name="quantity" [(ngModel)]="item.quantity" size="1" class="form-control"></td>
<td>{{(item.product | async)?.price | number: '.2'}}</td>
<td>{{(item.product | async)?.price * item.quantity | number: '.2'}}</td>
</tr>
</tbody>
<tfoot>
<tr>
<td colspan="2" class="text-right">
<strong>Total :</strong>
</td>
<td colspan="2" class="text-left">
?????????
</td>
</tr>
</tfoot>
我想计算 ShoppingCart 的总和.所以我想找到数据显示的 (2*5) + (1*6) = 16 的值.我该怎么做.
I want to calculate the sum of the ShoppingCart. So I want to find the value of (2*5) + (1*6) = 16 as the data shows. How do i do it.
这个plunker
推荐答案
问题出在这段代码中:
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);
});
两个调用:carts.map
和 carts.forEach
是同步的并且一个接一个地发生.但是产品的加载(通过 af.database.object
)是异步的,因此当您遍历尚未加载的 cartItem 产品时.
Two calls: carts.map
and carts.forEach
are synchronous and happen one after another. But loading of products (via af.database.object
) is asynchronous so when you iterating over cartItem products not been loaded yet.
解决方案是链接产品加载和总计算.请参阅此处.
The solution would be to chain product loading and total calculation. See here.
这篇关于我想用 Angularfire2 计算 Firebase 上 ShoppingCart 的总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!