说我正在构建一个从远程服务请求 bankAccountRawInput 的银行应用程序。然后应用计算 amountAfterInterest 并根据原始数据实例化一个新类 bankAccount。
原始数据接口(interface)
interface bankAccountRawInput {
public amount : number;
public interestRate : number;
}
数据提供者类
@Injectable()
export class bankAccount {
public amount : number;
public interestRate : number;
public amountAfterInterest : number
constructor(bankAccountRawInput : bankAccountRawInput) {
this.amountAfterInterest = this.amount * (1 + this.interestRate)
}
}
当 View 需要使用数据时,它会这样做
getBankAccount() {
this.bankAccountRawInput = callRemoteService.get();
this.bankAccount = new BankAccount(bankAccountRawInput);
}
并说用户可以选择利率,所以每次输入更改时我都会重新创建一个新类。
updateBankAccount(newValue) {
this.bankAccountRawInput.interestRate = newValue;
this.bankAccount = new BankAccount(bankAccountRawInput);
}
我担心总是使用 new 关键字来创建类和更新是否是个好主意。是否有更好的模式,例如通过为 bankAccount 创建更新方法来更新更改并重新计算值?
最佳答案
您需要更改您的模式,如下所示。
注意:您不需要使用public
。默认情况下,它是public
。请参阅内联注释
了解更多信息。您需要在 components
中执行必要的 imports
。
bankAccountRawInput.ts
interface bankAccountRawInput {
amount : number;
interestRate : number;
}
bankAccount.ts(提供商)
@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.
}
}
关于angular - Ionic/Angular类设计模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43631777/