首页 > 解决方案 > 如何获得 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
            ))
        );

标签: angulartypescriptreduce

解决方案


RxJs 的reduce功能与功能类似Array.prototype.reduce。你给它一个处理reduce和种子值的函数,当Observable完成时,从流中发出减少的值。以下是计算总和的方法:

this.nettoTotal$ = this.basket$.pipe(
  map((basket) => basket.lines),
  reduce((total, count) => total + count, 0)
);

推荐阅读