[英]Mapping an Angular HTTP Response properly
I am writing a simple Angular application that calls to an external API for data.我正在编写一个简单的 Angular 应用程序,该应用程序调用外部 API 以获取数据。 One of these API calls returns data in such a way:
这些 API 调用之一以以下方式返回数据:
{
"data": {
"items": [
{
// An Appointment object is here
},
{
...
}
]
}
}
I have an AppointmentService
which I use to call the API using the Angular HTTP library:我有一个
AppointmentService
,我用它来调用 API 使用 Angular HTTP 库:
getBookedAppointments(userID : number) : Observable<Appointment[]> {
return this.http.get<Appointment[]>('/api/url/goes/here')
.pipe(retry(2), catchError(this.handleError));
}
And finally, I am trying to get these Appointment objects into an Array:最后,我试图将这些 Appointment 对象放入一个数组中:
this.AppointmentService.getBookedAppointments(id).subscribe((appts : Appointment[]) => {
// appts contains {"data" : {"data": {"items" : [...]}}}
})
The issue being the fact that the API returns the array nested within data.items.问题在于 API 返回嵌套在 data.items 中的数组。 How can I properly map the response so that the array is not nested?
如何正确 map 响应,以便数组不嵌套?
You can use the map()
operator to return any object de-structuring from an API response.您可以使用
map()
运算符从 API 响应中返回任何 object 解构。 You should also have your HTTP return the correct type.您还应该让您的 HTTP 返回正确的类型。 Here's an example solution:
这是一个示例解决方案:
interface ApiResponse {
data: {
items: Appointment[];
}
}
getBookedAppointments(userID : number) : Observable<Appointment[]> {
return this.http.get<ApiResponse>('/api/url/goes/here')
.pipe(
map(({data}) => data.items)
retry(2),
catchError(this.handleError)
);
}
Note: I'm using object de-structuring inside the map()
operator.注意:我在
map()
运算符中使用 object 解构。 You could do map(response => response.data.items)
as well, but de-structuring helps reduce the number of properties you need to traverse.您也可以执行
map(response => response.data.items)
,但解构有助于减少您需要遍历的属性数量。
The easiest way is to create a model(class/interface) that replicates the content structure.最简单的方法是创建一个复制内容结构的模型(类/接口)。 For a data structure like this: {"data": {"data": {"items": [...]}}} create a class ( or an interface) like follows:
对于这样的数据结构: {"data": {"data": {"items": [...]}}} 创建一个 class (或接口),如下所示:
export class Response {
constructor() { }
public data: ResponseData = new ResponseData();
}
export class ResponseData {
public data: Item = new Item();
}
export class Item {
public items: Appointment[] = [];
}
export class Appointment {
constructor() { }
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.