Get Observable references from many to may middle foreign collection

北城余情 提交于 2019-12-24 07:27:31

问题


I have a many to many relationship:

[persons]x------1[personsPets]1------x[pets]

[persons]
id
name

[pets]
id
name

[personsPets]
id
personId
petId

Using @angular/fire and rxjs 6, I want a service to get the persons array with their pets each, like that:

this.personService.getPersons().subscribe(persons  => {
  const firstPersonPetNames: string[] = persons[0].pets.map(pet => pet.name)
  const secondPersonPetNames: string[] = persons[1].pets.map(pet => pet.name)

  console.log(firstPersonPetNames) // ['Copi Copi', 'Elemento', 'Adjetivo']
  console.log(secondPersonPetNames) // ['James Bond', 'Chaucha', 'Yo no fui']
})

回答1:


you could structure it like this:

getPersonsWithPets() {
  return this.getPersons().pipe( // get persons
    switchMap(persons => 
      // switch into combineLatest of persons mapped into their personPets fetch
      combineLatest(persons.map(person => this.getPersonsPets(person.id).pipe(
        switchMap(personPets => 
          // switch again into combine latest of personPets mapped into pet fetch
          combineLatest(personPets.map(personPet => this.getPet(personPet.petId))).pipe(
            // map into the person with the pets assigned
            map(pets => ({...person, pets}))
          )
      )))
    )
  );
}

possibly clean it up by breaking it down a little:

getFullPersonPets(personId) {
  return this.getPersonsPets(personId).pipe( // get personPets
    switchMap(personPets => 
      // switch into combine latest of personPets mapped into pet fetch
      combineLatest(personPets.map(personPet => this.getPet(personPet.petId)))
    )
  );
}

then:

getPersonsWithPets() {
  return this.getPersons().pipe( // get persons
    switchMap(persons => 
      // switch into combine latest of persons mapped into full pets fetch
      combineLatest(persons.map(person => this.getFullPersonPets(person.id).pipe(
        // map into the person with the pets assigned
        map(pets => ({...person, pets}))
      )))
    )
  );
}


来源:https://stackoverflow.com/questions/59078725/get-observable-references-from-many-to-may-middle-foreign-collection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!