从许多到可能中间的外国集合中获取 Observable 引用

Get Observable references from many to may middle foreign collection

我有一个多对多的关系:

[人]x------1[personsPets]1------x[宠物]

[persons]
id
name

[pets]
id
name

[personsPets]
id
personId
petId

使用@angular/fire 和 rxjs 6,我想要一个服务来获取 persons 数组和他们的宠物,就像这样:

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']
})

你可以这样构造它:

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}))
          )
      )))
    )
  );
}

可能通过稍微分解它来清理它:

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)))
    )
  );
}

然后:

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}))
      )))
    )
  );
}