Says I am building a banking app that request bankAccountRawInput from a remote service. The app then calculate the amountAfterInterest and instantiate a new class bankAccount 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 a view needs to consume the data, it does this
getBankAccount() {
this.bankAccountRawInput = callRemoteService.get();
this.bankAccount = new BankAccount(bankAccountRawInput);
}
and says the user can choose the interest 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 concern whether it is a good idea to always use new keyword to create classes and update. Is there a better pattern for example by creating an update method to bankAccount to update changes and recalculate value?
You need to change your pattern as shown below.
Note: You don't need to use public.By default, it is public. Please see the inline comments for more info. You need to do necessary imports inside the components.
bankAccountRawInput.ts
interface bankAccountRawInput {
amount : number;
interestRate : number;
}
bankAccount.ts (provider)
@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.
}
}