I'm pretty new to angular and rxjs and I just can't get it solved. I know my code is wrong, but i don't know how to write it correctly.
I'm fetching a JSON via a HTTP Request, the JSON contains data in an array. After that i want to loop through the array inside the JSON data and fetch additional data of another HTTP Endpoint.
I looked into flatMap, switchMap, and so on and I can't figure to combine these commands in my case.
Thank you guys!
My Code so far:
checkMatches() {
this.http.get<{
message: string,
result: any}>
(BACKEND_URL + 'matches')
.pipe(map((matchData) => {
return {matches: matchData.result.map(match => {
this.userService.getUserData(match.matchedUser).subscribe(userData => {
console.log(userData);
}
);
return {
id: match._id,
matchedUser: match.matchedUser,
firstMatch: match.firstMatch,
name: userData.userName,
img: userData.userImg,
status: match.status,
};
})};
}))
.subscribe(transformedMatchData => {
console.log(transformedMatchData);
});
}
As mentioned in comment below, you should re-think about this architecture, you should have a way to get all these records in one/two requests, not to fire 'N' requests if your loop length is 'N'.
Answering for the original posted question:
It looks like for every reponse of matches, you need to query APIS, you can use swicthMap()
along with forkJoin
here:
Using switchMap
would merge (BACKEND_URL + 'matches') say Parent observable
url observable along with next observables we create with its result, and also, it cancels new requests of if parent observable
emits again.
Using forkJoin
would make you wait for all the child observables to complete before emitting data.
checkMatches() {
this.http.get<{
message: string,
result: any}>
(BACKEND_URL + 'matches')
.pipe(switchMap((matchData) => {
return forkJoin(
...matchData.result.map(match => {
return this.userService.getUserData(match.matchedUser).pipe(
map((userData) => {
return {
id: match._id,
matchedUser: match.matchedUser,
firstMatch: match.firstMatch,
name: userData.userName,
img: userData.userImg,
status: match.status,
};
})
)
})
)
}))
.subscribe(transformedMatchData => {
console.log(transformedMatchData);
});
}