通过订阅响应读取的对象在初始化期间从其他属性设置 属性 值
Typescript set property value from other properties during initialization for objects read via response of subscription
我有一个简单的class
export class MyObj{
prop1: string;
prop2: string;
prop3: string;
}
我正在使用 HttpClient
:
从后端读取数据
this.httpClient.get<MyObj[]>(`backendUrl`).subscribe(
(response: MyObj[]) => {
//...some code...
}
);
现在我想在这个 class 中有一个 prop4
,它将在初始化期间从其他属性中获取它的值,并将在上面的 response
数组中可用。为此,我将 class 代码更改为以下代码,但它没有用。我怎样才能达到我想要的?
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;
}
}
试试
Object.assign(this.prop4, this.prop1, this prop2, this.prop3);
我认为你应该将原始 ApiResponse
与 MyObj
class 分开声明:
interface ApiResponse {
prop1: string
prop2: string
prop3: string
}
class MyObj {
prop1: string
prop2: string
prop3: string
// additional props
prop4: string
constructor(rawResponse: ApiResponse) {
this.prop1 = rawResponse.prop1
this.prop2 = rawResponse.prop2
this.prop3 = rawResponse.prop3
// additional props
this.prop4 = rawResponse.prop1 + rawResponse.prop2 + rawResponse.prop3
}
}
然后在 API 请求之后进行解析(可能是一些验证):
get<ApiResponse[]>('https://www.example.com')
.subscribe((response) => {
const myObjs = response.map(x => new MyObj(x))
// do something with myObjs
})
我有一个简单的class
export class MyObj{
prop1: string;
prop2: string;
prop3: string;
}
我正在使用 HttpClient
:
this.httpClient.get<MyObj[]>(`backendUrl`).subscribe(
(response: MyObj[]) => {
//...some code...
}
);
现在我想在这个 class 中有一个 prop4
,它将在初始化期间从其他属性中获取它的值,并将在上面的 response
数组中可用。为此,我将 class 代码更改为以下代码,但它没有用。我怎样才能达到我想要的?
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;
}
}
试试
Object.assign(this.prop4, this.prop1, this prop2, this.prop3);
我认为你应该将原始 ApiResponse
与 MyObj
class 分开声明:
interface ApiResponse {
prop1: string
prop2: string
prop3: string
}
class MyObj {
prop1: string
prop2: string
prop3: string
// additional props
prop4: string
constructor(rawResponse: ApiResponse) {
this.prop1 = rawResponse.prop1
this.prop2 = rawResponse.prop2
this.prop3 = rawResponse.prop3
// additional props
this.prop4 = rawResponse.prop1 + rawResponse.prop2 + rawResponse.prop3
}
}
然后在 API 请求之后进行解析(可能是一些验证):
get<ApiResponse[]>('https://www.example.com')
.subscribe((response) => {
const myObjs = response.map(x => new MyObj(x))
// do something with myObjs
})