My goal is to extract paginated data from a REST API and integrate it into my Angular application. The structure of the data sent by the API typically looks like this:
{
"next": null,
"results": [
{"id": 7, "name": "Alicia"},
{"id": 8, "name": "Ted"},
{"id": 9, "name": "Marshall"}
]
}
The next
field contains the URL for retrieving the next page of data. Since I don't know in advance how many pages are needed to load all the data, I need a flexible solution.
I have implemented a functional method that retrieves the data and can be viewed in this working example:
public loadPeople( next?:string ): void {
if(!next) next = 'api/1.json';
this.http.get(next)
.pipe(
map( (response: Response) => response.json())
)
.subscribe( (data: any) => {
this._people = this._people.concat(data.results);
this._peopleSubject.next(this._people);
if(data.next) this.loadPeople(data.next);
})
}
Although my current code works, I believe there might be a more efficient way to achieve this using RxJS operators to chain Observables. If anyone has suggestions on which operator to use or how to improve the code, I would appreciate the help. Thank you!