angular - 使用 RxJS 运算符从 API 获取并获取另一个然后组合结果
问题描述
我是 RxJS 的初学者,我的前端使用 angular。我有一个需要获取团队(Team [])的案例。
并使用该团队 id 获取所有成员 (Member[])。我需要返回每个团队的成员列表(团队,成员 [])。
如何使用 RxJS 运算符执行此操作?
例如:
来自 Teams API:[{team_id: number, 'others'}, ...]
来自会员 API:[{member_id: number, member_name: string}, ...]
我需要将数据组合到:[{team_id: number, members: [{member_id: number, member_name: string}, ...], ...]
解决方案
this.teamService.getTeams()
.pipe(
switchMap(teams => {
// in here we will get all teams in teams variable
const memberRequests = [];
// we will create an array of member requests based on the teams
teams.forEach(team => {
const request = this.memberService.getMembersByTeamId(team.id)
.pipe(map(members => {
// here we create new object which contains the team and its correspoing members
return {...team, members}
}))
memberRequests.push(request)
})
// in here we will call all member requests in parallel, and once all requests are completed we will get the response as array
return forkJoin(memberRequests)
})
).subscribe(items => {
console.log(items)
})
在上面的代码中,您将获得以下团队及其对应的成员,
[{team_id: number, members: [{member_id: number, member_name: string}, ...], ...]
推荐阅读
- reactjs - Rendering when mapping over normalized redux state
- node.js - Node JS web application deployment
- css - Material-UI change TextField color when input text is too long
- c# - How to record video with device camera in Unity?
- python - 将 column1 中的所有唯一项过滤为 Key,将 Column2 和 Column3 过滤为 key:value 作为来自常规 DataFrame 的嵌套 Dataframe 中的 Value
- java - Jersey 项目 Swagger-UI 在发送 @PathParam 时不发送 @HeaderParam
- csv - 将批量数据加载到 MariaDB 并报告错误
- dart - 由于 state.didChange() 调用,在 Forms 中使用时会出现缓慢的 Cupertino 输入字段
- reactjs - 按下按钮时将状态传递给子组件为空
- webrtc - 调用 navigator.mediaDevices.getUserMedia 时没有发现错误有什么原因吗