【问题标题】:AngularFire2/Rxjs the right way to do "nested subscriptions" with rxjs?AngularFire2/Rxjs 使用 rxjs 进行“嵌套订阅”的正确方法?
【发布时间】:2020-06-10 22:42:19
【问题描述】:

在我父亲餐厅的项目中使用 angular 和 firebase

我一直在想办法弄清楚 rxjs 一段时间。我正在尝试从我的数据库中读取数据以呈现在我的视图中。数据由类别和项目组成

Category
    id: str
    name: str
    desc: str
    order: num
Item
   id: str
   name: str
   desc: str
   price: str
   category: str
   order: num

为了在我的视图中显示数据,我正在尝试以这种格式提取数据

export interface CategoryItems {
  id: string;
  name: string;
  order: number;
  description?: string;
  items?: Array<Item>;
}

其中项目被定义为

export interface Item {
  id: string;
  name: string;
  description: string;
  price: string;
  category: string;
  order: number;
}

我最初编写的代码包含订阅以获取订阅中的项目以获取类别。当我开始更新数据时,这最终导致了一些不那么有趣的错误。回去我写了这个新代码来尝试解决这个问题。这正确返回了所有内容,除了项目作为可观察对象而不是正确格式返回。我认为它甚至根本没有订阅它们,也不知道如何正确映射它并一次或按顺序订阅它。

这是打字稿

this.afs.collection('categories', ref => ref.orderBy('order')).snapshotChanges().pipe(
      map(category => {
        let tempCat: any = []
        tempCat = category.map(a => {
          let temp: any = a.payload.doc.data()
          temp.id = a.payload.doc.id

          temp.items = []
          temp.items = this.afs.collection('items', ref => ref.where('category', '==', temp.name)).snapshotChanges().pipe(
            map(item => {
              let tempitem: any = []
              tempitem = item.map(b => {
                let temp2: any = b.payload.doc.data()
                temp2.id = b.payload.doc.id
                return temp2
              })
            })
          )
          console.log(temp)
          return temp
        })
        console.log(tempCat)
        return tempCat
      },


      )
    ).subscribe(result => {
      this.categories = result
    })

这是目前的结果

(5) [{…}, {…}, {…}, {…}, {…}]
0: {description: "test", name: "testyy", order: 0, id: "BuLw9S1NabBe86fVNvPc", items: Observable}
1: {description: "", name: "Plates", order: 1, id: "ob6W6fhjJREtpRq6QKAK", items: Observable}
2: {order: 2, name: "test3", description: "", id: "89d4HpLazuPSRBCQ2cWK", items: Observable}
3: {order: 2, name: "test4", description: "", id: "GNEcJu9gWCS67VYLYGom", items: Observable}
4: {name: "Deli Meal", description: "", order: 2, id: "L6Eq11MKjTk6RWqlSZoz", items: Observable}

所以我的问题是,我如何重写这部分代码以我想要的格式订阅它,或者我如何使用更改后的更好的格式来存储它以供我查看?

【问题讨论】:

    标签: javascript angular typescript rxjs angularfire2


    【解决方案1】:
    this.afs.collection('categories', ref => ref.orderBy('order')).snapshotChanges().pipe(
      switchMap(
        categorys => merge(
          categories.map(category => this.afs.collection('items', ref => ref.where('category', '==', category.name)).snapshotChanges())
        )
      )
    ).subscribe(arrayOfResults => { // do stuff });
    

    【讨论】:

      猜你喜欢
      • 2017-08-10
      • 2022-06-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-15
      • 2021-03-05
      • 2021-11-18
      相关资源
      最近更新 更多