在Angular中,如何将类的变量设置为函数的结果?

时间:2017-09-28 13:04:15

标签: html angular typescript

我希望能够实时更新另一个类的数组。

支队级别有一个属性CP,我希望陆军级别能够从其所有支队中获得总和,并使任何可以创建自己军队的东西都可以使用。 / p>

export class Army {
    cost: number;
    CP: number;
    name: string;

    Detachments: Detachment[];

    constructor() {
        this.cost = 0;
        this.name = "";
        this.Detachments = [];

        this.CP = this.getArmyCP();
    }

    getArmyCP() {
        let total = 0;
        for(let i=0; i<this.Detachments.length; i++) {
            total += this.Detachments[i].CP;
        }
        return total;
    }

}

我可以通过直接访问Army.getArmyCP()来查看该值,但是可以设置Army.CP来通过引用来访问该函数吗?

我已经能够在AngularJS中做到这一点,但我对Angular和TypeScript相当新,所以我不确定如何模仿这种行为。

1 个答案:

答案 0 :(得分:4)

您可以使用getter来解决此问题:

get CP(): number { return this.getArmyCP(); }

所以从外面你可以像普通变量一样使用它,它实际上会调用getter:

let myArmyCP = army.CP;