json - 将 JSON 响应对象值分配给 Angular 模型类对象
问题描述
我从 API 收到以下响应。
{
'firstName' : 'Sam',
'lastName' : 'Thomson',
'employeeAge' : 12
}
在我的 Angular 代码中,我试图将 JSON 响应映射到 Angular 类模型。这是类模型。
export class Employee{
constructor(){
this.empage = 0;
}
public firstName : String;
public lastName : String;
public empage : Number;
}
这是API调用的代码。
this.http.get('/api').subscribe((result : Employee) =>{
let emp = new Employee();
Object.assign(emp, result);
console.log('Result is ', emp);
})
收到的输出是:
{empage: 0, firstName: "Sam", lastName: "Thomson", age: 12}
如上所示,age
from 响应没有empage
从模型实例映射到。如何在不使属性名称相同的情况下实现相同的目标?
预期输出:
{empage: 12, firstName: "Sam", lastName: "Thomson"}
解决方案
需要注意的两件事
- 在声明
this.http.get('/api').subscribe((result: Employee)
中,响应被假定为 typeEmployee
,而事实并非如此。最好换成result: any
. - 据我所知,没有本地方法可以将一种类型的对象映射到另一种类型。以下是针对您的特定要求的解决方法
Object.keys()
export class AppComponent implements OnInit {
private employeeMap = ((source): Employee => {
const result = new Employee();
Object.keys(source).map((key) => {
if (key === 'employeeAge') {
result['empage'] = source[key];
} else {
result[key] = source[key];
}
});
return result;
});
ngOnInit() {
this.jsonService.getData().subscribe(
(result: any) => {
let emp: Employee = this.employeeMap(result);
console.log(emp);
}
);
}
}
工作示例:Stackblitz
推荐阅读
- python - [python]如何让字符串看起来像回显
- python - 如果图像是 tif float32,如何将图块读入张量?
- excel-2010 - 比较excel中的两个日期会给出错误的结果
- go - 在使零值有用时如何初始化默认为零的私有字段?
- javascript - 如何使用 JavaScript 向 Pixel 对象添加动态值?
- c# - C# char.isupper 在将数字放入字符串索引时抛出错误
- r - 我想给我的馅饼上色,但#numbers 不起作用。我究竟做错了什么?
- r - 循环超过 16 个数字,但每次不包括一个
- c# - 是否可以使用另一个 c# 项目运行 C# 项目
- video - Using -ss and -to to play a video using ffplay