How to write json pie angular get properties?

34 views Asked by At

I have a typescript class in my angular project.

export class CheckoutInfo {
    lines: CheckoutInfoLine[];
    taxRate: number;

    get subTotal(): number {
        return this.lines.reduce((acc: number, cur: CheckoutInfoLine) => acc + cur.total, 0)
    };

    get taxTotal(): number {
        return this.subTotal * this.taxRate;
    }

    get grandTotal(): number {
        return this.subTotal * (1 + this.taxRate);
    }

    constructor(lines: CheckoutInfoLine[] = [], taxRate: number = 0.7) {
        this.lines = lines;
        this.taxRate = taxRate;
    }
}

and I want to write this object using pipeline like following:

{{ myObject | json }}

But get parameters (subTotal,grandTotal,taxTotal) does not write in json string:

{ 
  "lines": [ 
   { "amount": "2", "product": { "id": 6, "name": "p-1", "price": 115.798 } }, 
   { "amount": 1, "product": { "id": 1, "name": "p-2", "price": 0 } } 
  ], 
  "taxRate": 0.7 
}
1

There are 1 answers

0
Andrei On

it is expected, as these properties aren't serialized by default. if you really need this behavior I would suggest you to override toJSON method

export class CheckoutInfo {
  toJSON() {
    return {
      ...this,
      subTotal: this.subTotal,
      taxTotal: this.taxTotal,
      grandTotal: this.grandTotal,
    };

  }