【问题标题】:Ionic / Angular class design pattern离子/角度类设计模式
【发布时间】:2017-04-26 19:55:43
【问题描述】:

说我正在构建一个从远程服务请求 bankAccountRawInput 的银行应用程序。然后应用程序计算 amountAfterInterest 并从原始数据实例化一个新类 bankAccount

原始数据接口

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)
  }
}

当视图需要消费数据时,它会这样做

getBankAccount() {
    this.bankAccountRawInput = callRemoteService.get();
    this.bankAccount = new BankAccount(bankAccountRawInput);
}

并表示用户可以选择利率,因此每次输入更改时我都会重新创建一个新类。

updateBankAccount(newValue) {
    this.bankAccountRawInput.interestRate = newValue;
    this.bankAccount = new BankAccount(bankAccountRawInput);
}

我担心总是使用 new 关键字来创建类和更新是否是个好主意。是否有更好的模式,例如通过为 bankAccount 创建一个更新方法来更新更改并重新计算价值?

【问题讨论】:

    标签: angular ionic-framework ionic2


    【解决方案1】:

    你需要改变你的模式,如下所示。

    注意:您不需要使用public。默认为public。请参阅inline comments 了解更多信息。您需要在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.
        }
    
    }
    

    【讨论】:

    • 如何将 rawInput 中的值设置为 BankAccount 类并计算/更新值?
    • 你能显示这个callRemoteService.get()的代码吗?你可以把它放在你原来的问题上。
    猜你喜欢
    • 2019-02-01
    • 2015-05-27
    • 1970-01-01
    • 1970-01-01
    • 2021-03-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-22
    • 1970-01-01
    相关资源
    最近更新 更多