我有这个简单的打字稿类:
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 + ')';
为了实现它,修改类的正确方法是什么?
现在我已经实现了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没有更新......
我认为我还要修改构造函数,但我不知道该怎么做......
由于
答案 0 :(得分:2)
您可以修改构造函数,例如:
constructor(values: { id: number, code: string, business: string }) {
this.idCustomer = values.id;
this.Code = values.code;
this.BusinessName = values.business;
}
将调用您的setter,以确保您的私人成员的计算。
当然,基于所使用的webapi,如果有可能某些参数不存在,您可以使用可选参数修改界面。