Reputation: 8717
I'm doing the Angular 7 tutorial wonder how to properly request a list of items if they are not on the top level, but nested:
Top-Level (works)
[
{ id: 123, name: 'Name 123'},
{ id: 124, name: 'Name 124'},
// ...
]
Nested (doesn't work)
{
message: 'x items found.',
data: [
{ id: 123, name: 'Name 123'},
{ id: 124, name: 'Name 124'},
// ...
]
}
Service
// ...
@Injectable({ providedIn: 'root' })
export class ItemService {
private apiUrl = 'api/items'; // items are in .data
constructor(private http: HttpClient) {}
getItems (): Observable<Item[]> {
// Here is the problem:
return this.http.get<Item[]>(this.apiUrl, {
pathToItems: 'data' // <- Pseudocode
});
}
}
Component
// ...
this.itemService.getItems()
.subscribe(items => this.items = items);
I could use subscribe()
in the service and return the content of .data
, but I think there should be a more simple solution. I need to keep the return type (array of Item
).
Any idea?
Thanks in advance!
Upvotes: 0
Views: 955
Reputation: 125
You can use RxJs filters like map or filter. That's one of the advantages when using RxJs (Observables). You can filter your data before you pass it to your component.
An example:
return this.http.get(ITEMS_URL).pipe(
filter(response => response.filter(data => data.message === "SUCCEEDED")),
map(response => response.map(data => data.items))
);
Upvotes: 2