I've got a service in an angular 4 app that is retrieving a variable number of pages from a back-end API.
I've looked at the answer here Angular 2 - Chaining http requests, which suggests using a flatMap, but this approach does not work since it requires that all requests are known beforehand. This wont work in my case since the number of requests and the url of each request is dynamic and not known.
The number of pages/requests is inferred from the result of the previous request. So if the previous request returns anything the next page is requested to see if there are any more items.
I tried the following
this.items = [];
_fetch(url, page) {
this.http.get(`${url}&pageSize=2&page=${page}`).subscribe(response => {
this.items.concat(response.json().items)
// if the list of items is not empty fetch another page
if (response.json().items.length > 0) {
this._fetch(url, ++page);
}
});
return Observable.of(this.items);
}
However this.items
is returned before the requests have a chance to complete so it is always returned as an empty list.
any ideas?