I am developing a program with Angular and TypeScript. I have a class called Signal, which has the next parameters:
export class Signal {
id: number;
obraId: number;
obra: string;
descripcion: string;
rangoInferior: string;
rangoSuperior: string;
unidades: string;
// more parameters
// I use ofJson method to create a Signal object
static ofJson(signalJson: ISignalJson): Signal {
return this.createSignal(signalJson.id, signalJson.obraId, signalJson.obra,
signalJson.descripcion, signalJson.rangoInferior, signalJson.rangoSuperior,
signalJson.unidades
);
}
static createSignal(id: number, obraId: number, obra: string,descripcion: string, rangoInferior: string, rangoSuperior: string,
unidades: string
): Signal {
const new_signal = new Signal();
new_signal.id = id;
new_signal.obraId = obraId;
new_signal.obra = obra;
new_signal.descripcion = descripcion;
new_signal.rangoInferior = rangoInferior;
new_signal.rangoSuperior = rangoSuperior;
new_signal.unidades = unidades;
return new_signal;
}
}
When I get the data from API, some parameters (descripcion
, rangoInferior
, rangoSuperior
) has null
value and I want to set to empty string. To get this, I use private properties and getters/setters.
Example:
private _descripcion: string;
public get descripcion(): string {
return this._descripcion;
}
public set descripcion(value: string) {
this._descripcion = value ? value : "";
}
The problem is that this object send with underscores fields to API and return an error.
{
"_descripcion": "lll5",
"id": 621284,
"obra": "INTEGRATION-TESTS",
"obraId": 378,
"_rangoInferior": '',
"_rangoSuperior": '',
"_unidades": ''
}
I have seen several answers to solve this:
- Make a
toJson
method and remove the underscores. - Use
Object.defineProperties
as below:Object.defineProperties(this, { _descripcion: { writable: true, enumerable: false }, descripcion: { get() { return this._descripcion; }, set(value: string) { this._descripcion = value ? value : ""; }, enumerable: true } } );
- Which is the best solution?
- Is there another answer which I should considerate?