[英]Assign JSON response object value to Angular model class object
我從 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
不會映射到模型實例的empage
。 如何在不使屬性名稱相同的情況下實現相同的目標?
預期輸出:
{empage: 12, firstName: "Sam", lastName: "Thomson"}
您可以使用接受三參數的 Object.assign 方法的重載版本,您可以將第三個值作為要覆蓋其值的對象傳遞參考鏈接:
只需使用:
Object.assign(emp, result, {empage: result.employeeAge});
需要注意的兩點
this.http.get('/api').subscribe((result: Employee)
,響應被假定為Employee
類型,而它不是。最好用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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.