angular - Angular - rest api json对模型的响应
问题描述
我如何将以下json响应转换为角度模型
{
data: [
{
id: 3,
country_id: 1,
name: "name1",
address: "address 1",
isActive: 1,
created_at: "2021-08-26T17:35:54.000000Z",
updated_at: "2021-08-26T17:35:54.000000Z",
country: {
id: 1,
name: "UAE",
},
},
],
message: "success",
status: true,
};
解决方案
我创建了几个接口和一个模型,它不是完整的代码,只是为了让您了解如何在 Angular 中创建数据模型类,希望对您有所帮助
export interface IResponse {
status?: boolean;
message?: string;
data?: Array<IUser>;
}
export interface IUser {
id?: number;
country_id?: number;
name?: string;
address?: string;
isActive?: number;
created_at?: Date;
updated_at?: Date;
country?: ICountry;
}
export interface ICountry {
id?: number;
name?: string;
}
//===========================================================
// Model for above interface
//==========================================================
export class User {
id: number;
country_id: number;
name: string;
address: string;
isActive: number;
created_at: Date;
updated_at: Date;
country: ICountry;
constructor(data?: IUser = null) {
this.id = data?.id;
this.country_id = data?.country_id;
this.name = data?.name;
this.address = data?.address;
this.isActive = data?.isActive;
this.created_at = data?.created_at;
this.updated_at = data?.updated_at;
this.country = data?.country;
}
}
//===========================================================
// Suppose you have api method which will return this data
//==========================================================
ngOnInit() {
let response: IResponse = fetchData();
let userList: Array<User> = [];
response?.data?.forEach((user) => {
userList.push(new User(user))
});
}
fetchData(): IResponse {
return {
data: [
{
id: 3,
country_id: 1,
name: "name1",
address: "address 1",
isActive: 1,
created_at: "2021-08-26T17:35:54.000000Z",
updated_at: "2021-08-26T17:35:54.000000Z",
country: {
id: 1,
name: "UAE",
},
},
],
message: "success",
status: true,
} as IResponse
}
推荐阅读
- c - C - 可以添加邻居的图节点(无向)
- firebase - 错误:无法获取 Firebase 项目项目名称。请确保该项目存在并且您的帐户有权访问它
- eclipse - 自动代码完成不适用于 Eclipse
- python - 在更多线程中使用 Python gRPC 客户端存根时可以提高性能吗?
- python - 如何在 Pandas 中替换 Panel 并将其导出到 excel
- delphi - Delphi 最快的 FileSize 大小 > 10gb
- python - 尝试使用 shutil.move 移动文件时出现 WinError 32 和 Errno 13
- angular - 可观察到的“完成”后退订
- javascript - 强大的可视化 HTML 编辑器到 JavaScript 应用程序
- javascript - 希望从 Google 工作表创建 XML 提要