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 ?
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),'
);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With