从许多到可能中间的外国集合中获取 Observable 引用 [英] Get Observable references from many to may middle foreign collection

查看:17
本文介绍了从许多到可能中间的外国集合中获取 Observable 引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个多对多的关系:

I have a many to many relationship:

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

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

这篇关于从许多到可能中间的外国集合中获取 Observable 引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆