httpclient - Angular 7 HttpClient 响应类型作为类
问题描述
我正在尝试使用 httpclient 从 http get 调用中转换我的响应并创建我创建的类的实例。
问题
HttpClient 似乎没有使用其响应对象的属性创建我的类的新实例。请帮忙!
我尝试过创建一个类与接口。不知道我还需要在这里做什么。
我的课
export class Escalation {
constructor(private NAME: string, private DESCRIPTION: string) { }
public get name() {
return this.NAME;
}
public set name(name: string) {
this.NAME = name;
}
public get description() {
return this.DESCRIPTION;
}
public set description(description: string) {
this.DESCRIPTION = description;
}
}
我的服务
public getEscalation(escalationName) {
return this.http.get(`${this.globals.baseRestUrl}/companies/escalations/${escalationName}`);
}
我的组件
public escalation: Escalation = new Escalation('', '');
this.companiesService.getEscalation(escalationName).subscribe(
(escalationResponse: Escalation) => this.escalation = {
...escalationResponse
}, (error: any) => {
console.log(error);
}
);
预期结果
我希望我的响应在 api 回调时被强制转换为类型 Escalation (My class)。
api 的 实际结果返回一个对象,如下所示:
{
NAME: 'Escalation 1',
DESCRIPTION: 'This is a test description'
}
但最终 this.escalation 返回 undefined
我希望我解释得很好。如果您需要更多信息,请告诉我!
解决方案
这(escalationResponse: Escalation)
行代码并不是真的要转换来自HttpClient 的响应,而是要推断它是什么类型。
您可以考虑将代码调整为this.escalation = new Escalation(escalationResponse.NAME, escalationResponse.DESCRIPTION)
我相信this.escalation = { ...escalationResponse }
无论如何只是解构属性。
推荐阅读
- python - 用户条目作为熊猫中的列名
- stored-functions - 如何刷新 ADS 存储过程中的缓冲区?
- mysql - Bitnami Wordpress phpmyadmin 无法连接到 mysql
- html - Internet Explorer 11,如何设置只读样式?
- php - 如何从 API 结果中选择特定值
- python - 简单来说super()的用例是什么
- ios - 对 AudioKit FM 振荡器参数执行基本算术运算:插值和时间转换
- ssl - Kubernetes 添加域名和 SSL
- javascript - Angular:覆盖嵌套组件的scss样式
- java - Java 时区数据库与 IANA 数据