In my coding project, I have a function that creates multiple requests:
fetchData(): Array<Observable<AxiosResponse<Data>>> {
const data = [];
for (let i = 1; i <= end; i++) {
data.push(
this.http.get<Data>(
generateUrl(i),
),
);
}
return data;
}
Additionally, there is a controller function involved:
@Get()
retrieveData() {
return this.appService.fetchData().forEach(x => {
x.subscribe(y => {
// the goal here is to aggregate and merge the data from each request into a single JSON response
});
});
}
I am currently seeking advice on how to effectively combine all the data retrieved from each individual request in the controller method and output it as a unified JSON object. Any suggestions?
If I attempt the following approach:
@Get()
retrieveData() {
const mergedData = [];
return this.appService.fetchData().forEach(x => {
x.subscribe(y => {
mergedData.push(...y.data);
});
return mergedData;
});
}
I quickly realized that this method will not succeed since return mergedData
would execute prior to the actual completion of .subscribe(...)
The structure of y.data
consists of an array of objects such as:
[
{key:"xyz", value:123 },
{key:"abc", value:666 }
]