如何用另一个observable填充observable并返回observable

问题描述 投票:0回答:2

我正在研究rxjs项目,我使用json-server作为数据库提供程序。我被困在获得一个我需要用另一个集合填充的集合。

我有收集比赛和收集比赛。内部集合Match,我只有tournamentId,但我的类Match也包含Tournament实例。

class Match{
    id:number;
    ...
    tournamentId:number;
    tournament: Tournament;
}

class Tournament{
    id:number;
    ...
    name:String;
}

我需要从db调用2次。首先获得所有比赛,然后获得所有比赛。

我需要返回已经填充了锦标赛的Match Observable。

get(): Observable<Match> {
    return Observable.create(obs => {
      tournamentService.get().pipe(toArray()).subscribe(tournaments => {//tournaments = [torunament1, tournament2]
        super.get().pipe(map(x => { let m = new Match(x); m.populateTournament(tournaments); obs.next(m); return m; })).subscribe(() => {
          obs.complete();
        });
      });
    });
  }

obs.complete()被立即调用,因此我最终只创建了一个可观察的匹配。我正在尝试在地图管道中填充Match with Tournament,并将其作为obs.next(m)发送到那里。我不知道这是否也很聪明。

tournamentService.get()和super.get()分别返回锦标赛的Observables和未填充的Match(具有相同属性的JS {object})。

我如何逐个匹配()并将它们全部发送到用户呼叫完成()之后?

typescript rxjs observable
2个回答
0
投票

您不应该创建自己的可观察对象,您可以使用现有的运算符。我认为mergeMap,switchMap和combineLatest都可以在这里工作。

你应该结合这两个可观察量:

  get(): Observable<Match> {
    return combineLatest([super.get(), tournamentService.get()]) // Combine both Observables when both emit
      .pipe(map(([match, tours])=> { // Destructuring array of emitted values
        let m = new Match(match);
        m.populateTournament(tours);
        return m; // Return match combined with tournaments
    }))
  }

0
投票

我设法用'withLatestFrom'管道解决了这个问题。

 get(): Observable<Match> {
    let matchesObs = super.get();
    let tournamentsObs = tournamentService.get().pipe(toArray());

    return matchesObs.pipe(
      withLatestFrom(tournamentsObs),
      map(([m, t]) => {
        let match = new Match(m as Match);
        match.populateTournament(t as Tournament[]);
        return match;
      })
    );
  }
© www.soinside.com 2019 - 2024. All rights reserved.