5

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 ?

2 Answers 2

7
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),'
    );
Sign up to request clarification or add additional context in comments.

Comments

0
this.total$ = this.list$.pipe(
  mergeMap((list: number[]) => from(list).pipe(
    reduce((totalPrice: number, currentPrice: number) => totalPrice + currentPrice)
  ))
);

This is another solution you can use

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.