本文介绍了从许多到五月中间的外国收藏中获得可观察的参考的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有很多关系:

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

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

[persons]
id
name

[pets]
id
name

[personsPets]
id
personId
petId

使用@ angular/fire和rxjs 6,我想要一个服务来将人员阵列与宠物一起放置,就像这样:

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

推荐答案

您可以这样构造它:

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

然后:

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

这篇关于从许多到五月中间的外国收藏中获得可观察的参考的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-23 21:25