Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 6 : calculating the sum of a list (Observable)

Tags:

angular

rxjs

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' inside the map operator is a Order[] instead of a Order. What am I doing wrong ?

like image 333
Wolf359 Avatar asked Jul 01 '18 18:07

Wolf359


1 Answers

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

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.

It will be something like this

   this.total$ = this.list$.pipe(
      map(order => order.reduce((total, price) => total + price, 0),'
    );
like image 52
Antoniossss Avatar answered Oct 05 '22 07:10

Antoniossss