6

TL;DR 是否可以在 observable 的管道内使用 forkJoin?

全文:我有一个服务,它返回 Observable 对象数组。对于这些对象中的每一个,我都需要再次调用返回可观察对象的服务,并对每个结果应用另一个操作。

op1 ->[] ----> op2 --> op3
          \\-> op2 --> op3
           \-> op2 --> op3

我目前的解决方案是这样的:

    this.tournamentParticipantService.getNotAssigned(this.tournamentId).subscribe(
      (players: Player[]) => {
        let dict = {};
        players.forEach(player => {
          dict[player.id] = this.teamService.add(
            { 
                id: 0,
                members: [],
                tournament: this.tournamentId,
                name: player.name + " " + player.surname
            })
            .pipe(
              map((team: Team) => 
                this.teamMemberService.add({ player: player.id, team: team.id })
              ))
        });
        forkJoin(dict).subscribe(result => console.log(result));
     });

我想摆脱第一个订阅并改用管道。问题是 forkJoin 的教程将其显示为对象或数组被传递到的源,而不是管道的一部分。

从地图内部调用 forkJoin

.pipe(
    map(value=>forkJoin(value))

返回Observable<Observable<resolved forkJoin arguments>>我可能需要递归订阅。好像不是什么好办法。

将 fJ 放入不带参数的管道中

this.tournamentParticipantService.getNotAssigned(this.tournamentId).pipe(
      map((players: Player[]) => players.map(
        (player: Player) => this.teamService.add({ id: 0, members: [], tournament: this.tournamentId, name: player.name + " " + player.surname })
          .pipe(
            map((team: Team) => {
              let pipe = new JsonPipe();
              console.log("team: " + pipe.transform(team) + " player: " + pipe.transform(player));
              this.teamMemberService.add({ player: player.id, team: team.id });
            })))),
      forkJoin
    ).subscribe((result: [[Observable<void>]]) => {
      console.log(result)
      result[0].forEach(element => {
        element.subscribe(res => console.log(res));
      });
    });

以可观察物的奇怪纠结结构结束。这似乎也不是一个好办法。

甚至可以从管道内部使用 forkJoin 吗?

4

2 回答 2

20

我认为您缺少的东西forkJoin将返回一个可观察的,因此标准map不是您要寻找的:您需要使用其中一个以适当方式处理可观察结果的地图(即switchMapexhaustMap, mergeMap):

.pipe(
    switchMap(value => forkJoin(getThingOne(value), getThingTwo(value)))
.subscribe(([thing1, thing2]) => 
{

})
于 2019-07-03T20:18:47.920 回答
0

解决方案采用的最终形式是:`

this.tournamentParticipantService.getNotAssigned(this.tournamentId).pipe(
  map((players: Player[]) => players.map(
    (player: Player) => this.teamService.add({ id: 0, members: [], tournament: this.tournamentId, name: player.name + " " + player.surname })
      .pipe(
        map((team: Team) =>
          this.teamMemberService.add({ player: player.id, team: team.id }))
      ))),
  mergeMap((tasks: Observable<Observable<void>>[]) => forkJoin(tasks)),
  mergeMap((tasks: Observable<void>[]) => forkJoin(tasks))
).subscribe(() => {
  this.loadTeams();
});

`

于 2019-07-17T07:27:17.623 回答