I have to do multiple GET Requests to load data from an external page.
The response of the a request might return a flag that indicates that there is more data to load: "nextPage" : "/v1/catalog/products?page=2&pageSize=10",
Below is the code of my function.
I tried to implement a do while loop but I couldn't make it work. I guess there is also a smarter way to do this - maybe Switchmap?
Old Version
loadCatalog() {
return new Promise((resolve, reject) => {
this.http.get<Catalog[]>(ZUORA_URL + '/v1/catalog/products?page=1&pageSize=10', { headers })
.pipe(map(data => data))
.subscribe(data => {
this.catalog = data;
resolve(true);
});
});
}
I want to load the complete data and store it in one place. How can I loop until there is no additional nextpage? - loading one page after another is now working but I'm still struggeling to store the responses...
Updated Version
getProducts(url, dataSoFar = []): Observable<any[]> {
if (!url) {
return of (dataSoFar);
} else {
url = ZUORA_URL + url;
}
return this.http.get<any>(url, { headers }).pipe(
switchMap(p => this.getProducts( p.nextPage, [...dataSoFar, ...p.data]))
);
}
getData() {
return this.getProducts('/v1/catalog/products');
}