Recently, I integrated a search engine into my application and now I need to gather all the data available for a particular resource, such as all the posts made by a user.
The response I receive from my API looks something like this:
{
"count": 2,
"next": "http://127.0.0.1:8000/resource/?page=2",
"previous": null,
"results": [
{
"resource_data": "data"
}
]
}
What I aim to achieve is to create a method within my service that will return a promise containing an array comprising data from all pages.
Unfortunately, my understanding of TypeScript and JavaScript is somewhat limited, leaving me unable to devise an elegant solution.
The resolution:
Following the recommendation provided in the selected answer, I have crafted the following code snippet to be included in my service:
getAllMDPosts(): Observable<MDPost[]> {
return this.getRecursivelyMDPosts(`${environment.apiUrl}/mdposts/`);
}
private getRecursivelyMDPosts(url: string, results?: MDPost[]): Observable<MDPost[]> {
if (results === undefined) {
results = [];
}
return this.http.get(url).pipe(
switchMap(response => {
if (response.next) {
return this.getRecursivelyMDPosts(response.next, results.concat(response.results));
} else {
return of(results.concat(response.results));
}
})
);
}
While I typically avoid ternary operators, opting instead to incorporate more detailed conditionals, I still find myself needing to adjust them nonetheless.