Search code examples
javascriptangularobservablesubscriptionangular2-observables

Angular 7 nested observables


I have two collections: persons and pets. Every pet has personId. My target is to get all persons and foreach of them to add his/her pets in single json. What I did so far is:

this.personService.getPersions().subscribe(persons => {
  const personsWithPets = persons.flatMap(person => this.petService.getPetsByPersonId(person._id)
    .subscribe(petsData => {
      person.pets = petsData;
      return person;
    }, (err) => {
     console.log(err);
    }));
  this.persons = personsWithPets; // This is fired before previous subscribe
}, (err) => {
  console.log(err);
});

What I do wrong? Why this.persons = personsWithPets; is fired before subscription finish?


Solution

  • Updated added comments

    Another one: stackblitz

    this.service.getPersons().pipe(switchMap((per:any[])=>{
           //create an array of observables
           const obs=per.map(per=>this.service.getPet(per.id));
           //call all of them in forkjoin
           return forkJoin(obs).pipe(map(pets=>
             //pets is an array, in pets[0] is the response of getPet(1), 
             //in pets[1] is the response of getPet(2)
             pets.map((pet,i)=>{
               return {
                 ...per[i], //all the properties of the person
                 pets:pet   //+ in pets an array with the pets of the person
                 }
             })
           ))
         })).subscribe(res=>this.res=res)