angular - 如何获得 Observable来自 Nativescript Angular 中另一个 Observable 的 reduce 操作?
问题描述
我试图在我的角度组件中显示一个可观察的总数,如下所示:
total$ | async
它应该是购物篮中所有行的计算总和:
totalAmount = sum of (price * unitsOrdered)
我的接口是:
export interface IBasketLine {
unitsOrdered?: number;
price?: number;
}
export interface IBasket {
header?: IBasketHeader;
lines?: Array<IBasketLine>;
}
我的 Angular 组件包含2 个 observables:
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
))
);
解决方案
RxJs 的reduce
功能与功能类似Array.prototype.reduce
。你给它一个处理reduce和种子值的函数,当Observable
完成时,从流中发出减少的值。以下是计算总和的方法:
this.nettoTotal$ = this.basket$.pipe(
map((basket) => basket.lines),
reduce((total, count) => total + count, 0)
);
推荐阅读
- python - 如何使用 Keras 和 python 计算神经网络架构的 MAC?
- regex - 使用正则表达式验证 Laravel 字段
- pine-script - 如何在图表中画一条线?
- java - 在与 Facade 模式协作的同时应用设计模式
- java - 如果 spring-boot 上下文部署失败,Tomcat 多上下文部署将停止整个过程
- html - 在两个 div 之间放置带有文本的行
- android - 如何清除改造实例?
- python - 如何使用 .set() 在 python cv2 中调整实时视频的大小?
- javascript - 将对象的键映射到对象值的数组
- nginx - 合并 2 个不同文件夹 nginx 的目录列表