Class and design properties

I have this simple typescript class:

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);
    }

}

      

The first 3 properties ( idCustomer, Code, BusinessName ) are evaluated from the WebApi response or application code.

I want that every time these property values ​​change sValue ans sTitle is updated with this formula:

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

      

What is the correct way to change the class to implement it?

UPDATE 1

Now I have implemented the GET / SET method and they work if I create 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 at this point the values ​​are obtained from the mapping / subscription WebApi, which only pass 3 properties (idCustomer, Code, Business Name) sValue and sTitle are not updated ...

I think I need to change the constructor too, but I don't know how to do that ...

thank

+3


source to share


1 answer


You can change your constructor like this:

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 so that your private members are computed.

Of course, based on the webapi used, you can change the interface with optional parameters if it is possible that some are missing.

+2


source







All Articles