RXJS while loop for pagination

Viewed 6933

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 next data from. What I want to do is that the subscribe method updates the angular component every time a new page is available.

I’m new to the reactive programming model. How can I implement a while loop or a sequence of Observables?

This works for the first page:

getAllPeople(): Observable<Person[]> {
    let nextUrl = http://swapi.co/api;

    let source = Observable.create(observer => {

            this.http.get(nextUrl, { headers: this.headers })
            .map(response => {
                    let body = response.json();
                    nextUrl = body.next;
                    return nextUrl != null ? body.results as Person[] : null;
                }
            )
            .retry(5)//send same request based on the url of the previous request till the field next is null
            .catch(error => observer.error(error))
            .subscribe(persons => {
                    if (persons !== null) {
                        observer.next(persons)
                    }
                }
            );

        //observer.complete();
    })


    return source;
}

Edit: I added the retry() method. I hope it is easier to understand what I intend to do. After the first request, it sends more requests to the same URL. Unfortunately, it doesn't use the new URL I get from the previous request.

http://swapi.co/api/?page=1 -> http://swapi.co/api/?page=2 -> http://swapi.co/api/?page=3 -> null

I don’t know how many requests I need to retrieve all data.

2 Answers
Related