RxJs Observable Pagination

后端 未结 3 636
隐瞒了意图╮
隐瞒了意图╮ 2020-11-27 05:29

First: This is the first project in which I am using RxJs, I thought I will learn best by using it.

I found this answer: Turning paginated requests into an Observabl

3条回答
  •  攒了一身酷
    2020-11-27 05:52

    Here is my solution using the rxjs operators expand, reduce and empty using the HttpClient module:

    Suppose your API response is an object containing shaped like the following

    interface Response {
      data: items[]; // array of result items
      next: string|null; // url of next page, or null if there are no more items
    }
    

    You could use expand and reduce like so

    getAllResults(url) {
      return this.http.get(url).pipe(
        expand((res) => res.next ? this.http.get(res.next) : EMPTY),
        reduce((acc, res) => acc.concat(res.data), [])
      );
    }
    

提交回复
热议问题