Search code examples
angulartypescriptclass-transformer

"Hydrate" class instance from JSON object


I have this class:

import { AccountRow } from './account-row';
export class Account {
  id?:number;
  name:string;
  rows: AccountRow[];
  public getTotal?(): number {
    let total: number = 0;
    if (!this.rows || this.rows.length == 0) {
      return total;
    }
    for(let r of this.rows) {
      total += r.amount;
    }
    return total;

  }
}

I try to populate it with the following:

export class HomePage {
  accountForm: FormGroup;
  addRowForm: FormGroup;
  activeAccount: Account;

  constructor(public navCtrl: NavController) {
    // fixture for testing
    this.activeAccount = {
      name: "January balance",
      rows: [
        { description: "Car insurance", amount: 45.5, date: new Date() },
        { description: "Car insurance", amount: -20.5, date: new Date() }
      ]
    };
    console.log(this.activeAccount.getTotal());

  }
}

Values are asigned correctly but it seems object asignation is destroying getTotal method, when I execute the code it throws:

Error: Uncaught (in promise): TypeError: this.activeAccount.getTotal is not a function
TypeError: this.activeAccount.getTotal is not a function

I wonder if it is possible to do this without destroying instance methods and without implementing an initializer constructor or factory method


Solution

  • There is no way to do it in the language. Use class-transformer https://github.com/pleerock/class-transformer.