I'm having a very hard time implementing a recursive HTTP request functionality in an Angular application using HttpClient.
I have an API that serves some data for me. The API puts the data into pages, meaning that the first response contains a URL to the next page and so on. (it's a search request to the public HAPI FHIR server)
I found this link online explaining how I can achieve this, but it does not work for me: https://medium.com/angular-in-depth/rxjs-understanding-expand-a5f8b41a3602
This is what I got at the moment:
In my service class:
getFhirVitalSigns(patientId: string): Observable<any> {
let url = this.vitalSignsUrl + "?subject:Patient=" + patientId;
console.log("Starting process for getting all vital signs")
return this.getPage(url).pipe(
expand(({next}) => next ? this.getPage(next) : empty()),
concatMap(({content}) => content)
);
}
getPage(url:string): Observable<{
content: any[];
next: string | null;
}> {
return this.http.get(url).pipe(
map((response:any) => ({
content: response.entry,
next: this.getNextPage(response)
}))
);
}
getNextPage(response: any): string | null {
let url: string | null = null;
for (let link of response.link){
if (link.relation = "next"){
url = link.url;
}
}
console.log("Found new page: " + url);
return url;
}
And this is the code snippet where I call my service method:
this.vitalSignsService.getFhirVitalSigns(this.patientId!).subscribe(
(test) => console.log(test)
);
The problem now is: the code ends in an infinite loop. It looks like that the code does not realize when there is no new page anymore.
Can someone help me?
This is how the pages look like:
{
"resourceType": "Bundle",
"id": "67ea2654-e1a6-4d21-b242-66c99024df64",
"meta": {
"lastUpdated": "2020-09-02T19:32:30.124+00:00"
},
"type": "searchset",
"total": 30,
"link": [
{
"relation": "self",
"url": "http://hapi.fhir.org/baseR4/Observation?_count=1&subject%3APatient=1457293"
},
{
"relation": "next",
"url": "http://hapi.fhir.org/baseR4?_getpages=67ea2654-e1a6-4d21-b242-66c99024df64&_getpagesoffset=1&_count=1&_pretty=true&_bundletype=searchset"
}
],
"entry": [
{
"fullUrl": "http://hapi.fhir.org/baseR4/Observation/1457319",
"resource": {
// actual data of first data item
}
]
}