0

I have the following code:

init() {
  const requisitionData = this.login().pipe(
    map(response => response.data.token),
    switchMap(loginData => this.getRequisitions(loginData)),
    map(response => response.data),
    map(requisitions => this.processRequisitions(requisitions)),
  );
  requisitionData.subscribe();
}

the getRequisitions() calls a search endpoint that returns paginated data like so:

{
    data: [{        
        title: '...',
        reference: '...',
    }],
    meta: {
        cursor: {
            current_page: 1,
            from: 1,
            to: 50,
            next: 2,
            prev: null,
            last_page: 2137,
            per_page: 50,
            total: 106824
        }
    },
    message: 'Result List'
}

My current code in init() only retrieves the first set of results (50 entries), performs some light processing on the data and saves it into the database (the processRequisitions). How do I change my code to:

  • Get the first set of result
  • Get the value of meta.cursor.last_page
  • Pass the next_page value and call the same endpoint until last_page is reached.
Edwin
  • 886
  • 2
  • 13
  • 32
  • Does this answer your question? [RxJs Observable Pagination](https://stackoverflow.com/questions/35254323/rxjs-observable-pagination) – Tal Ohana Dec 31 '19 at 07:29

1 Answers1

2

You can replace the switchMap and replace with expand and takeWhile

const requisitionData = this.login().pipe(
     map(response => response.data.token),
     switchMap(loginData => 
       getRequisitions(loginData).pipe(
          expand(()=>this.getRequisitions(loginData)),
          takeWhile(res=>{
             const {cursor}=res.meta;
             return cursor.next+1<curosr.last_page
          }),
          map(response => response.data),
          map(requisitions => this.processRequisitions(requisitions)),
       ),
  );
Fan Cheung
  • 10,745
  • 3
  • 17
  • 39
  • hmm.. replacing the `switchMap` seem to cause the `loginData` (which is actually a string of the login token) to be passed into the `takeWhile`, together with the response of the `getRequisitions` function. How do I prevent the login token to be passed? – Edwin Jan 02 '20 at 02:39
  • sorry my mistake, i should mov the expand to inner observable. Updated the code – Fan Cheung Jan 02 '20 at 06:50
  • Unfortunately the updated code still does not work - I added a `console.log` in the first line of the `takeWhile` and in the first time the value of `res` is still the login token – Edwin Jan 02 '20 at 07:46