Maureen Moore

Maureen Moore

  • NA
  • 206
  • 0

Pipe isn't returning the right values

Jul 22 2020 6:31 PM
I have a pipe that is supposed to add the sub totals together to return the grand total but it just returns the sub total. It returns sub_total = product_price * quantity; and not the sum of the sub totals.
This is my pipe:
  1. @Pipe({  
  2. name: 'grandtotal'  
  3. })  
  4.   
  5. export class GrandTotalPipe implements PipeTransform {  
  6. transform(product_price: number, quantity: number) {  
  7. var totals = [];  
  8. var sub_total;  
  9. sub_total = product_price * quantity;  
  10. totals.push(sub_total);  
  11. var i;  
  12. var grand_total = 0;  
  13. for (i = 0; i < totals.length; i++) {  
  14. grand_total += totals[i];  
  15. }  
  16. return grand_total;  
  17. }  
  18. }  
This is how I call the pipe in the HTML:
  1. <div>Grand Total {{ product_price | grandtotal: quantity : sub_total : grand_total : totals }}</div>  
 
When I remove "var totals = [];", I get "cannot read property push of undefined." When I just use "var totals;", I get "Subsequent variable declarations must have the same type. Variable 'totals' must be of type 'any[]', but here has type 'any'."
I've tried putting "var totals = [];" everywhere. I've tried putting it before the transform function and I've tried putting it in the component. It can't go anywhere except where it is now but that's leading to my issue so that's no good.

Answers (6)