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

标签 html angular typescript

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

Detachment 类有一个属性 CP,我希望 Army 类能够从其所有 Detachment 中获取其总和,并使创建自己的 Army 的任何对象都可以访问该属性。

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 相当陌生,所以我不确定如何模拟这种行为。

最佳答案

你可以用 getter 来解决这个问题像这样:

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

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

let myArmyCP = army.CP;

关于html - 在 Angular 中,如何将类的变量设置为函数的结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46469913/

相关文章:

css - 如何使用百分比宽度使一行 5 个 <divs> 响应?

html - 响应式设计如何正确使用css媒体查询

html - 标题部分的视差效果

JavaScript 创建对象结构数组

javascript - ES6 mixin 的 Typescript 定义

JavaScript JSON 解析问题 ($.getJSON)

javascript - 无法使用 "ng new"命令通过 ng cli 创建新项目

angular - 处理有关 Bootstrap 的 'unmet peer dependency' 的 NPM 警告,当它们未在 Angular 中使用时

node.js - 发生未处理的异常 : Cannot find module '@angular/compiler-cli/ngcc'

typescript - TypeScript 中带有泛型的条件类型