Angular 6:计算列表的总和(Observable) [英] Angular 6 : calculating the sum of a list (Observable)

查看:38
本文介绍了Angular 6:计算列表的总和(Observable)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 Orders 数组,想创建一个 observable 来给出计算出的价格总和.我使用的是 Angular 6.

I have an array of Orders and want to create an observable that gives the calculated sum of prices. I'm using Angular 6.

import { map, reduce, isEmpty } from 'rxjs/operators';
import { Observable } from 'rxjs';

  list$: Observable<IOrder[]>;
  total$: Observable<number>;
  empty$: Observable<boolean>;


ngOnInit() {
    this.list$ = this.service.asList.asObservable(); // asList is a BehaviorSubject
    this.empty$ = this.list$.pipe(isEmpty());
    this.total$ = this.list$.pipe(
      map(order => order.price),  // <-- Property 'price' does not exist on type 'IOrder[]'
      reduce((total, price) => total + price, 0)
    );
}

'order' 在 map 操作符中是一个 Order[] 而不是 Order.我做错了什么?

'order' inside the map operator is a Order[] instead of a Order. What am I doing wrong ?

推荐答案

Property 'price' does not exist on type 'IOrder[]

这意味着您的 Observable 不会一一返回元素流(这就是您在这里所期望的),而是一次返回整个数组 - 发出单个结果.立即对数组执行 reduce,而不是 map 到属性.

That means that your Observable does not return stream of elements one by one (and that's what you expect here), but whole array at once - single result is emitted. Instead of map to property, perform reduce on array right away.

它会是这样的

   this.total$ = this.list$.pipe(
      map(order => order.reduce((total, price) => total + price, 0),'
    );

这篇关于Angular 6:计算列表的总和(Observable)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆