Angular Firebase:take(1) 返回多个文档

问题描述 投票:0回答:1

我正在尝试从 Firestore 的 Products 集合中获取单个文档。 ProductService 处理查询并返回订阅:

//ProductService
export class ProductService {
...  
getByPermalink(permalink: string) {
    return this.db.collection('products', ref => ref.where('permalink','!=', permalink ))
      .valueChanges({ idField: 'id' })
      .pipe(take(1)) 
  }
}

然后在我的组件上调用它:

//ProductComponent
this.productService.getByPermalink(this.permalink).subscribe((res: any) => {
   this.product = res
   console.log('product', this.product)
})

所有这些都有效,但它似乎不支持

take(1)
调用,并在查询有多个匹配项时返回多个文档。

任何帮助将不胜感激。

angular firebase angularfire
1个回答
1
投票

take(1)
使您只能获取一次数据(而不是随着数据库的变化而随着时间的推移获取更新)。但是该数据将包含您的查询返回的任何内容。如果您只想要一个文档,则需要限制查询,而不是可观察的。您可以使用
limit
函数执行此操作:

return this.db
  .collection("products", (ref) =>
    ref.where("permalink", "!=", permalink).limit(1)
  )
  .valueChanges({ idField: "id" })
  .pipe(take(1));
© www.soinside.com 2019 - 2024. All rights reserved.