简体   繁体   English

rxjs switchMap和嵌套的Observables

[英]rxjs switchMap and nested observables

I want to ask my firestore for an array of documents which are holding information referencing to other documents. 我想向我的Firestore索要一系列文件,这些文件中包含引用其他文件的信息。

get "user" document => returns ids of "items" documents => foreach(get "item" document) 获取“用户”文档=>返回“项目”文档的ID => foreach(获取“项目”文档)

getUserOwnedItems(uid:string):Observable<Item[]>{
    return this.firestore
          .collection<any>(`members`, ref => ref.where('uid', '==', uid))
          .valueChanges()
          .pipe(
            switchMap(ids => { // these ids are representing the "item" ids 
              return ids.map(id => {
                return this.firestore
                  .doc<Item>(`items/${id.itemId}`)
                  .valueChanges();
              });
            })
            ,concatAll() // <-- Iam not sure about this
          );
}

The problem is Iam expecting an observable with an Array of Items. 问题是Iam期望可观察到一系列物品。 Instead I get a observable of Item back. 相反,我得到了一个可观察到的物品。

How can I convert this to 我如何将其转换为

Observable<Item[]>

? Thanks in advance! 提前致谢!

My Structure in firestore looks as follows: 我在Firestore中的结构如下所示:

members : [
 {
  uid:string,
  itemId:string,
  ...
 }
]

items : [
 {
  id:string,
  ...
 }
]

The Use Case in other words: I want to get all Items related to a specific user identified by its uid. 换句话说,用例:我想获取与由其uid标识的特定用户有关的所有项。

Update: I found out that all concats mergs or forkJoins are not working in this scenario because the firebase observables will never be completed. 更新:我发现所有concats mergs或forkJoins在这种情况下均不起作用,因为firebase可观察对象将永远不会完成。

I could do something like ... 我可以做类似...

return this.firestore
   .doc<Item>(`items/${id.itemId}`)
   .valueChanges().pipe(first());

But this will break my realtime connectivity. 但这会破坏我的实时连接。 Besides this every call of this function will result in reads on FireStore which will cost money. 除此之外,每次调用此函数都将导致在FireStore上进行读取,这将花费大量资金。

You probably wanted to use combineAll instead of concatAll if you need an Observable<Item[]> . 如果需要Observable<Item[]>则可能要使用combineAll而不是concatAll

combineAll combineAll

Flattens an Observable-of-Observables by applying combineLatest when the Observable-of-Observables completes. 当Observable-of-Observables完成时,通过应用CombineLatest来展平Observable-of-Observables。

concatAll concatAll

Converts a higher-order Observable into a first-order Observable by concatenating the inner Observables in order 通过将内部Observable按顺序并置,将高阶Observable转换为一阶Observable

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM