RxJs / Angular:通过地图循环中的订阅获取其他数据



我对angular和rxjs很陌生,我只是无法解决它。 我知道我的代码是错误的,但我不知道如何正确编写它。

我正在通过HTTP请求获取JSON,JSON包含数组中的数据。 之后,我想遍历 JSON 数据中的数组并获取另一个 HTTP 端点的其他数据。

我研究了flatMap,switchMap等,我无法想象在我的情况下组合这些命令。

谢谢你们!

到目前为止我的代码:

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);
});
}

正如下面的评论中提到的,你应该重新考虑这个架构,你应该有办法在一个/两个请求中获取所有这些记录,而不是在循环长度为"N"时触发"N"请求。

回答原始发布的问题:

看起来对于匹配的每个响应,您都需要查询 API,您可以在此处将swicthMap()forkJoin一起使用:

使用switchMap将合并(BACKEND_URL + 'matches') say Parent observableurl 可观察量以及我们用其结果创建的下一个可观察量,并且,它会取消 ifparent observable再次发出的新请求。

使用forkJoin会让您等待所有子可观察量完成,然后再发出数据。

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);
});
}

最新更新