0

I have a method within a service (angular) which I am using as a generic one to get a list of resources from a json api spec endpoint.

The endpoints are limited to 10 resources per request, and they return meta information such as total page size.

Within this one method, what I want to be able to do is perform a request if the page size is 1 then just return the request, however if the page size is greater than 1 then I want to loop through and map all of the resources together.

So for example, if I'm doing a request for blog posts and I have 100. The page size is limited to 10, I'll have a response like this...

{
    "data": [
        ...
    ],
    "paginationMeta": {
        "pageSize": 10,
        "totalItems": 100
    }
}

After I have got this, I want to loop through 10 times to get the rest of the data and piece it together.

I currently have this code...

return this.apiService.list('posts').pipe(switchMap((response: any) => {
    if (response.paginationMeta.pageSize === 1) {
        of(response);
    }

    // We know the current page will be 2
    let currentPage: number = 2; 
    const resource = response.data;
    const requests: any[] = [];

    while (currentPage <= response.paginationMeta.pageSize) {
        requests.push(this.apiService.list('posts', currentPage));

        currentPage++;
    }

    forkJoin(requests).pipe(map((responses: any[]) => {
        responses.forEach((apiResponse: any) => {
            resource.push(apiResponse);
        });

        return of(resource);
    }));   
});

I believe this is way off the mark of what I'm trying to achieve. I have done some googling and can't seem to find anything that will help me achieve this.

  • So you want to iterate all 10 pages or just the 10 results you got? – martin Jul 22 '19 at 09:04
  • I want to iterate through all the 10 pages and then map the result from that into one main resource object which I will return at the end of the method. Sorry, I don't think I made that clear –  Jul 22 '19 at 09:05
  • Maybe this can help https://stackoverflow.com/questions/44097231/rxjs-while-loop-for-pagination – João Ghignatti Jul 22 '19 at 09:19
  • @JoãoGhignatti that link seems very outdated, however it may help me a bit –  Jul 22 '19 at 09:26

0 Answers0