Ionic / Angular class design pattern
Says I am creating a banking application that requests bankAccountRawInput from a remote service. The application then calculates the AfterInterest sum and instantiates a new bankAccount class from the raw data.
Raw data interface
interface bankAccountRawInput {
public amount : number;
public interestRate : number;
}
Data provider class
@Injectable()
export class bankAccount {
public amount : number;
public interestRate : number;
public amountAfterInterest : number
constructor(bankAccountRawInput : bankAccountRawInput) {
this.amountAfterInterest = this.amount * (1 + this.interestRate)
}
}
When the view needs to consume data, it does so
getBankAccount() {
this.bankAccountRawInput = callRemoteService.get();
this.bankAccount = new BankAccount(bankAccountRawInput);
}
and says that the user can select the percentage rate, so every time the input changes, I recreate a new class.
updateBankAccount(newValue) {
this.bankAccountRawInput.interestRate = newValue;
this.bankAccount = new BankAccount(bankAccountRawInput);
}
I am concerned about whether it is always worth using the new keyword to create classes and update. Is there a better pattern, for example by creating an update method for bankAccount to update the changes and recalculate the value?
source to share
You need to change your template as shown below.
Note. You don't need to use public
. The default is public
. For more information see inline comments
. You need to do imports
in components
.
bankAccountRawInput.ts
interface bankAccountRawInput {
amount : number;
interestRate : number;
}
bankAccount.ts (vendor)
@Injectable()
export class BankAccount implements bankAccountRawInput {//implements interface like this.
amount : number;
interestRate : number;
amountAfterInterest : number
constructor() {//no need to inject interface here now
this.amountAfterInterest = this.amount * (1 + this.interestRate)
}
bankMethod() : void {
console.log("Hi");
}
}
page.ts
export class MyPage{
constructor(public bankAccount : BankAccount ){//inject your service here
}
getBankAccount() {
this.bankAccount.bankMethod();//no need to use `new` keyword here.Angular does it on behalf of us when we injected in the constructor.
}
}
source to share