I have a simple class
export class MyObj{
prop1: string;
prop2: string;
prop3: string;
}
I am reading data into it from backend using HttpClient
:
this.httpClient.get<MyObj[]>(`backendUrl`).subscribe(
(response: MyObj[]) => {
//...some code...
}
);
Now I want to have a prop4
in this class that will get its value from other properties during initialization and will be available in the above response
array. To achieve this I changed the class code to below but it didn't work. How can I achieve what I want?
export class MyObj{
prop1: string;
prop2: string;
prop3: string;
prop4: string;
constructor(prop1, prop2, prop3) {
this.prop1 = prop1;
this.prop2 = prop2;
this.prop3 = prop3;
this.prop4 = prop1 prop2 prop3;
}
}
CodePudding user response:
try with this:
export class MyObj{
constructor(public prop1, public prop2, public prop3, private prop4) {
this.prop4 = this.prop1 this.prop2 this.prop3;
}
}
the public/private can be changed according to your needs
EDIT: With @jonrsharpe commentary, I was aware of the mistake... But if it doesn't work, I'm going to give you another possible solution:
export class MyObj{
prop1: string;
prop2: string;
prop3: string;
prop4?: string;
}
this.httpClient.get<MyObj[]>(`backendUrl`).subscribe(
(response: MyObj[]) => {
response.map(
_item => _item.prop4 = _item.prop1 _item.prop2 _item.prop3
);
//...some code...
}
);
CodePudding user response:
Try with
Object.assign(this.prop4, this.prop1, this prop2, this.prop3);