Reputation: 157
this.weekDates.forEach((wdate) => {
this.billingservice.getbill(this.formatDate(wdate)).subscribe(info => {
this.objArray.push(info)
// console.log(info)
})
// console.log((wdate));
})
this.objArray.forEach((outer, index) => {
console.log(outer, "outerloop-", index);
outer.forEach(inner => {
// this.sumPrice = inner.grandTotol
this.sumPrice = this.sumPrice + (inner.grandTotol)
console.log(inner.grandTotal, "innerloop")
});
});
How to determine sumPrice value here in my case it shows me undefined
Upvotes: 0
Views: 37
Reputation: 39432
You're trying to calculate the result of something that has not even been evaluated yet.
The objArray
will get populated asynchronously and that too after the this.objArray.forEach((outer, index) => { ... })
function has executed.
What you are supposed to do instead is to calculate the sum only once the whole objArray
is populated. In order to do that, you could use forkJoin
and wait for all the this.billingservice.getbill(this.formatDate(wdate))
calls to happen. Once that's done you could just calculate the total from the returned array.
Something like this:
forkJoin(
...this.weekDates.map(wdate =>
this.billingService.getBill(this.formatDate(wdate))
)
).subscribe((res: any[]) => {
this.sumPrice = res.reduce((acc, item) => acc + item.grandTotal, 0);
});
Here's a Working Code Sample for your reference.
Upvotes: 2