RXJS while loop for pagination

前端 未结 2 1073
花落未央
花落未央 2021-02-08 12:56

I try to query all people data from the swap api. The URL swapi.co/api/people returns an object with an people array and the URL(swapi.co/api/people/?page=2) where I get the nex

2条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-02-08 13:43

    By using the expand operator you can create a new Observable sequence for each value that is returned. To stop the expand from creating any new sequences, once we get a next URL that is null, we can return an empty Observable to stop expanding our sequences. Finally, we can use a reduce operator to aggregate the different pages of data into one array that we then emit back to the original subscriber. This can be accomplished as follows:

    public getAllPeople(): Observable {
        return Observable.create(observer => {
              this.getPage("http://swapi.co/api/people/")
                .expand((data, i) => {
                    return data.next ? this.getPage(data.next) : Observable.empty();
                })
                .reduce((acc, data) => {
                    return acc.concat(data.results);
                  }, [])
                .catch(error => observer.error(error))
                .subscribe((people) => {
                      observer.next(people);
                      observer.complete();
                });
        });
    }
    
    private getPage(url: string): Observable<{next: string, results: Person[]}> {
      return this.http.get(url, { headers: this.headers })
                .map(response => {
                        let body = response.json();
                        return {
                          next: body.next,
                          results: body.results as Person[]
                        };
                    }
                );
    }
    

    Demo

提交回复
热议问题