Mapping an Angular HTTP Response properly
You can use the map()
operator to return any object de-structuring from an API response. You should also have your HTTP return the correct type. 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. You could do map(response => response.data.items)
as well, but de-structuring helps reduce the number of properties you need to traverse.