Issue
This is my code
//Service method
private cartObs$: BehaviorSubject<CartItem[]> = new BehaviorSubject(null);
getCartItems(): Observable<CartItem[]> {
return this.cartObs$.asObservable();
}
//method in component
sum$: Observable<number>;
this.sum$ = this.cartService
.getCartItems()
.pipe(map((cart) =>
cart.reduce((total, item) => total + item.qty, 0)));
i need to calculate sum of qty in rxjs. am getting error if obeservable is empty
how to calculate sum in rxjs with empty list
I am following similar to this arrayof obervable sum
Thanks in advance
ERROR
ERROR TypeError: Cannot read property 'reduce' of null
at MapSubscriber.eval [as project] (https://cddm0ddd.ddd.app/src/app/components/header/header.component.ts:17:50)
at MapSubscriber._next (https://cugm0.csb.app/node_modules/rxjs/_esm5/internal/operators/map.js:47:29)
at MapSubscriber.Subscriber.next (https://cugm0.csb.app/node_modules/rxjs/_esm5/internal/Subscriber.js:73:12)
at BehaviorSubject._subscribe (https://cugm0.csb.app/node_modules/rxjs/_esm5/internal/BehaviorSubject.js:34:18)
at BehaviorSubje
Solution
I would assume that your this.cartObs$
is of type BehaviorSubject and by default it require to set default value. So I think you are setting default value to null instead of an empty array or you are emmiting null to your subject.
So I see two options here:
Set to empty array private cartObs$: BehaviorSubject<CartItem[]> = new BehaviorSubject([]);
Second fix reducer so it can handle null values ( I think this is safest way since then you dont care if someone will push null into your subject)
this.sum$ = this.cartService
.getCartItems()
.pipe(map((cart) => cart ?
cart.reduce((total, item) => total + item.qty, 0)) : 0);
cart ? cart.reduce((total, item) => total + item.qty, 0)) : 0
this means if cart is not null run reduce of its null return 0