【发布时间】:2019-09-08 03:20:06
【问题描述】:
假设我有一个返回以下 JSON 结构的 api:
{
"Response": {
"status": {
"code": "SUCCESS",
"message": "owner found",
"count": "1"
},
"owners": [
{
"ownerId": "12345",
"name": "Example Person",
"cars": [
{
"make": "Toyota"
"year": "2004"
"model": "Camry"
}
]
}
]
}
}
我想将此 json 结构映射到这些打字稿模型中:
export class ApiResponse{
constructor(
public status: Status,
public owners: Owner[]
) {}
}
export class Status {
constructor(
public code: string,
public message: string,
public count: number
) {}
}
export class Owner{
constructor(
public ownerId: number,
public name: string,
public cars: Car[]
) {}
}
export class Car{
constructor(
public make: string;
public year: string;
public model: string;
)
}
根据我对 Angular 7 的理解,你可以使用 rxjs 中的 pipe 和 map 来实现:
this.http.get(url).pipe(
map((data: any[]) => data.map((item: any) => new ApiResponse(
new Status(
item.status.code,
item.status.message,
item.status.count),
...
使用它我可以映射一个 JSON 对象,但我不确定如何处理映射数组和嵌套数组。
我应该如何使用嵌套数组映射 JSON?
【问题讨论】:
-
如果您的模型定义实际上只是属性列表,那么它们在功能上等同于接口。因此,没有必要实例化新对象,因为没有任何收获——TS 强制对接口和类进行类型检查。只需将
Observable返回给组件进行渲染。
标签: json angular typescript rxjs angular7