I am currently working with a class that looks like this:
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;
}
}
When trying to populate it with the following code:
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());
}
}
Although values are assigned correctly, it appears that object assignment is causing the getTotal method to be lost. When attempting to execute the code, an error is thrown:
Error: Uncaught (in promise): TypeError: this.activeAccount.getTotal is not a function
TypeError: this.activeAccount.getTotal is not a function
I am curious to know if there is a way to achieve this without losing instance methods or having to implement an initializer constructor or factory method.