【发布时间】:2018-11-16 03:22:32
【问题描述】:
我试图在我的角度组件中显示一个可观察的 total,如下所示:
total$ | async
它应该是购物篮中所有行的计算总和:
totalAmount = sum of (price * unitsOrdered)
我的界面是:
export interface IBasketLine {
unitsOrdered?: number;
price?: number;
}
export interface IBasket {
header?: IBasketHeader;
lines?: Array<IBasketLine>;
}
我的 Angular 组件包含 2 个可观察对象:
basket$: Observable<IBasket>;
nettoTotal$: Observable<number>;
可观察的购物篮$ 是从我的 ngrx 存储中初始化的,并且所有行在我的视图中都是可见的。这是我的 ngOnInit 函数:
ngOnInit(): void {
this.store.dispatch(new basketActions.Load());
this.basket$ = this.store.pipe(
select(fromBasket.getBasket)
);
this.nettoTotal$ = this.basket$.pipe(
map((basket) => basket.lines),
reduce( ??? )
);
}
如何使用 reduce 函数,以便在我的视图中获得正确的总数?
更新:
这确实有效:
this.nettoTotal$ = this.basket$.pipe(
map((basket) => {
if (basket) {
return basket.lines;
} else {
return [];
}
}),
map((lines) => {
let total = 0;
for (const line of lines) {
const val = Math.round((line.bestelaantal * line.nettoprijs * 100) / 100);
total = total + val;
}
return total;
})
);
更新 2:
当我直接调用返回 IBasket 的 Observable 的服务方法时,此代码有效:
this.nettoTotal$ = this.basketService.getBasket().pipe(
map((basket) => basket.lines),
map((lines) => lines.map((line) => line.nettoprijs * line.bestelaantal).reduce(
(accumulator, linePrice) => accumulator + linePrice,
0
))
);
当我使用来自我的商店的 observable 时,此代码不起作用:
this.nettoTotal$ = this.basket$.pipe(
map((basket) => basket.lines),
map((lines) => lines.map((line) => line.nettoprijs * line.bestelaantal).reduce(
(accumulator, linePrice) => accumulator + linePrice,
0
))
);
【问题讨论】:
-
在这种情况下,尝试
subscribe到basket$Observable 并将响应记录到控制台以检查究竟是什么错误。
标签: angular typescript reduce