I am currently working on a project using rxjs and json-server as the database provider. I have encountered an issue while trying to populate one collection with another.
The two collections in question are Match and Tournament. The Match collection contains a tournamentId, but also has a Tournament instance within it.
class Match{
id:number;
...
tournamentId:number;
tournament: Tournament;
}
class Tournament{
id:number;
...
name:String;
}
To achieve this, I need to make two separate calls to the database - one to retrieve all tournaments and another to get all the matches.
My goal is to return an Observable of Match that has been populated with the associated Tournament.
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();
});
});
});
}
The issue I am facing is that obs.complete() is getting called right away, resulting in only one Match being created in the observable. I am attempting to populate the Match with the Tournament in the map pipe, and then send it using obs.next(m). However, I am unsure if this approach is the most efficient.
tournamentService.get() and super.get() both return Observables of the Tournament and unpopulated Match respectively (JS {object} with the same attributes).
What would be the best way to call next() for each match individually and only call complete() once all matches have been sent to the subscriber?