typescript – 类和计算属性

我有这个简单的打字稿类:

customer.ts

export class Customer {

    public idCustomer: number;
    public Code: string;
    public BusinessName: string;

    public sValue: any;
    public sTitle: string;

    constructor(values: Object = {}) {
        Object.assign(this, values);
    }

}

前3个属性(idCustomer,Code,BusinessName)是从WebApi响应或应用程序代码中提取的.

我想要的是每次这3个属性更改值时,sValue和sTitle都会使用以下公式进行更新:

sValue = idCustomer
sTitle = BusinessName + ' (cod:' + Code + ')';

修改类以实现它的正确方法是什么?

更新1

现在我已经实现了GET / SET方法,如果我实例化一个新的Customer类并更改值,它们就可以工作

export class Customer {

    //public idCustomer: number;
    //public Code: string;
    //public BusinessName: string;
    private _idCustomer: number;
    get idCustomer():number {
        return this._idCustomer;
    }
    set idCustomer(newIdCustomer: number)
    {
        this._idCustomer = newIdCustomer;
        this.sValue = this.idCustomer;
    }

    private _Code: string;
    get Code(): string {
        return this._Code;
    }
    set Code(newCode: string) {
        this._Code = newCode;        
        this.sTitle = '(Cod:' + this._Code + ') ' + this._BusinessName;
        alert();
    }

    private _BusinessName: string;
    get BusinessName(): string {
        return this._BusinessName;
    }
    set BusinessName(newBusinessName: string) {
        this._BusinessName = newBusinessName;
        this.sTitle = '(Cod:' + this._Code + ') ' + this._BusinessName;
    }


    public sValue: any;
    public sTitle: string;

    constructor(values: Object = {}) {
        Object.assign(this, values);        
    }

}

但是在这一刻,值是来自WebApi映射/订阅只传递3个属性(idCustomer,Code,Business Name)的sValue和sTitle没有更新…

我认为我还要修改构造函数,但我不知道该怎么做…

谢谢

最佳答案 您可以修改构造函数,例如:

constructor(values: { id: number, code: string, business: string }) {
    this.idCustomer = values.id;
    this.Code = values.code;
    this.BusinessName = values.business;
}

它将调用您的setter,以确保您的私人成员的计算.

当然,基于所使用的webapi,如果可能的某些参数不存在,您可以使用可选参数修改该接口.

点赞