我是Angular的新手,并找到了一种可销售的模块化方法来填充类中的派生变量集。
export class Calculator {
constructor(
public x?: number,
public y?: number,
public total?: number,
) {
this.total = this.x + this.y;
}
}
我应该发生的是,Angular应该知道total
和x
,y
之间存在依赖关系。每当x
或y
更新时,Angular应该重新评估total
。
我知道这可以通过写作来完成,
this.calculator.total = this.calculator.x + this.calculator.y
在ngOnInit
控制器或onchange
触发器。但如果我有很多派生变量,它就不具有可扩展性和模块性。确实,Class只是打字稿而且它不知道Angular。你可以通过替代方案来帮助我。
如果使用getter总计效率不高你可以更新Calculator
类
export class Calculator {
constructor(
private _x?: number,
private _y?: number,
public total?: number,
) {
this.total = this.x + this.y;
}
private update() {
this.total = this.x + this.y;
}
set x(val) {
this._x = val;
this.update();
}
set y(val) {
this._y = val;
this.update();
}
}
现在,只要对象内发生更改,就可以重新计算多个属性。