问题描述
我有以下代码,我正在尝试计算添加到购物车中的所有物品的总数。当我使用reduce时,我什么也没回来,但是在进行故障排除时,我在那儿添加了一张地图(注释掉了代码),并打印了一个值。我可以在此处添加更多代码,但是您知道一切正常。我可以看到购物车中的数据是一个对象数组。我只需要迭代并计算总价格。 请告知。
this.store.select('cart').pipe(reduce((accumalatedTotal,cartItem) => accumalatedTotal + (cartItem.price),0))subscribe((val:number) => console.log("===>>>",val));
//this.store.select('cart').pipe(map(cartItem => cartItem.price)).subscribe((val:number) => console.log("===>>>",val));
使用注释掉的地图,我可以打印物品价格,但使用reduce看不到任何东西。
解决方法
尝试这样
this.store.select('cart').pipe(reduce((accumalatedTotal,cartItem) => accumalatedTotal += (cartItem.price),0)).subscribe((val:number) => console.log("===>>>",val));
我建议您创建一个自定义选择器,例如:
export const getCartProductsTotalPrice = createSelector(
selectShoppingCartState,(state: CartState) => {
return state.cart.reduce((total,current,idx) => total += current.prodotto.price,0)
;});
并在component.ts中只需调用
return this.store.pipe(select(getCartProductsTotalPrice));
使用map
运算符和array上的reduce函数获得总数。
this.store.select('cart').pipe(
map(cart => cart.reduce((accumalatedTotal,cartItem) =>
accumalatedTotal + (cartItem.price * cartItem.quantity),0)
)
).subscribe((val:number) => console.log("===>>>",val))
Reduce运算符将函数应用于源Observable发出的第一项,然后将函数结果与源Observable发出的第二项一起反馈回函数,继续此过程,直到源Observable发出其最终项目并完成,然后从Reduce返回的Observable会发出从函数返回的最终值。
如果您的购物车的价值是一个项目流,则reduce运算符将很有用。在您的情况下,您只能从商店中选择“购物车”,即一个商品。
代码分解
this.store.select('cart').pipe(
)
从您的商店中选择购物车的值
[
{id: 1,price: 100},{id: 2,price: 50},...etc
]
地图运算符将cart变量提供给函数
cart => cart.reduce(
(accumalatedTotal,{price,quantity}) =>
accumalatedTotal + (price * quantity),0)) )
上面计算出购物车中的价格之和
,在我的猜测中,有两种可能性。一种是错别字,第二种是不完整的。当Observable完成时,reduce运算符将显示结果。