angular - Ionic/Angular类设计模式

标签 angular ionic-framework ionic2

说我正在构建一个从远程服务请求 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/

相关文章:

angular - 公共(public)或私有(private) - Angular 2 组件类方法混淆

angular - Ionic 4 Console.Log() 未显示在函数中

angular - Ion-list 是否应该自动在列表项上添加箭头?

javascript - 谷歌地图在 Ionic 2 应用程序中不起作用

javascript - Ionic 2 数据在网络不存在时重新加载

css - 呈现内容之前页脚出现问题

angular - 在可观察值的初始加载期间未加载的值

来自文件 :///protocol 的 Angular2

browser - 如何在不同的端口上提供 Ionic 应用程序?

ionic-framework - 在 Ionic 框架中使用搜索功能