Reputation: 2552
I have this simple typescript Class:
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);
}
}
The first 3 properties( idCustomer, Code, BusinessName ) are valorized from WebApi response or by app code.
What I want is that each time these 3 property changes value, the sValue ans sTitle get updated with this formula:
sValue = idCustomer
sTitle = BusinessName + ' (cod:' + Code + ')';
What is the properly way to modify the class in order to implement it?
Now I have implemented GET/SET Method, and they works if I instantiate a new Customer class and change the values
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);
}
}
But in this moment is the values comes from a WebApi mapping/subscribe that pass only the 3 properties ( idCustomer, Code, Business Name ) the sValue and sTitle are not updated...
I think that I have also to modify the contructor, but I don't know how to do it...
Thanks
Upvotes: 4
Views: 7008
Reputation: 21799
You can modify your constructor for example as:
constructor(values: { id: number, code: string, business: string }) {
this.idCustomer = values.id;
this.Code = values.code;
this.BusinessName = values.business;
}
which will call your setters, that ensures the computation of your private members.
Of course based on the webapi used, you can modify the interface with optional parameters if it is possible that some of them are not present.
Upvotes: 2