Reputation: 149
I'm struggling to find a solution to this.
I have the following model, loaded via a promise thru a service.
export class Something {
id: number;
someTime: string;
items: [
{
id: number;
description: string;
unit: string;
portion: number;
std: number;
}
]
}
It has mock data:
const SOMETHINGS: Something[] = [
{
id: 0,
someTime: 'Now',
items: [
{
id: 0,
description: 'A',
unit: 'ml',
portion: 275,
std: 64
},
{
id: 1,
description: 'B',
unit: 'g',
portion: 50,
std: 378
},
....
]
}
]
The actual values are irrelevant, but I need to access each portion and std values. Multiply them and finally SUM them together.
Like so:
275 * 64 = 17600
50 * 378 = 18900
total = 36500
Inside my component I have assigned the returned data to a local array like so.
something: Something[] = [];
constructor( private somethingService: SomethingService ) {}
ngOnInit(){
this.getSomething();
}
getSomething(){
this.somethingService.getSomething().then(something => this.something = something);
}
This value is not inside a repeated section of my template so I can't use an *ngFor type approach.
It would seem logical to use something like:
calcTotal(){
let totals:array<Number>;
let gross:number = 0;
this.something.forEach((items) => total.push( items.portion * items.std ));
totals.forEach((total:number) => gross += total));
return {
total: totals;
}
}
But this doesn't work..
I simply don't know how to access each item and extract the two values, multiply them, save them for later extract the next pair and so on. Then finally take all the results and sum them up and pass it to the view.
Any help would be appreciated.
Steve
Upvotes: 0
Views: 214
Reputation: 3800
you could do this when you get your data and subscribe to it from your service.
this.somethingService.getSomething()
.then((data) => {
this.data = data;
this.totals = this.calculateValues(data);
});
// With the model you have up there it would look like this.
calculateValues(data){
let total = 0;
data.map( somethingObj => {
somethingObj.items.map(itemObj => {
total += (itemObj.portion * itemObj.std);
})
})
return total;
}
Upvotes: 1