【问题标题】:How to get particular document data with id ? | AngularFire 5.1.1 | Cloud Firestore | Documents如何获取带有 id 的特定文档数据? |角火 5.1.1 |云火库 |文件
【发布时间】:2019-06-01 21:36:03
【问题描述】:

我正在使用数据访问服务从 firebase firestore 获取数据。

如何使用 snapshotChanges() 方法获取带有 id 的特定文档数据

getProduct(id: number): Observable<Product> {
    this.productsDocuments = this.angularfirestore.doc<Product>('products/' + id);
    this.product = this.productsDocuments.snapshotChanges().pipe(
      map(changes => changes.map(a => {
        const data = a.payload.doc.data() as Product;
        const id = a.payload.doc.id;
        return { id, ...data };
      }))
    );
    return this.product

我希望 this.product 返回文档值和文档 ID

谢谢!!

【问题讨论】:

  • this.product 的返回会包含 id。所以this.product.id 是文档的id。要通过返回访问它,您必须使用 this.service.getProduct().subscribe((product) =&gt; { console.log(product.id) })
  • @Swoox - 感谢您的回复,您的方法将起作用,但 snapshotChanges() 不起作用,错误属性 'map' 在类型 'Action>' 上不存在。

标签: angular firebase google-cloud-firestore angularfire5


【解决方案1】:

文档只是一个对象{[field]: value} 集合是文档[document]的容器。

您正在尝试获取单个文档/对象,但问题是您无法直接映射到它。我认为您想要获取整个集合,然后映射所有文档。

getProduct(id: number): Observable<Product> {
    const productsDocuments = this.db.doc<Product>('products/' + id);
    return productsDocuments.snapshotChanges()
      .pipe(
        map(changes => {
          const data = changes.payload.data();
          const id = changes.payload.id;
          return { id, ...data };
        }))
  }

收藏

getProduct(id: string): Observable<Product[]> {
    const productsDocuments = this.db.collection<Product[]>('products');
    return productsDocuments.snapshotChanges()
      .pipe(
        map(changes => changes.map(({ payload: { doc } }) => {
          const data = doc.data();
          const id = doc.id
          return { id, ...data };
        })),
        map((products) => products.find(doc => doc.id === id)))
  }

【讨论】:

    猜你喜欢
    • 2019-06-01
    • 1970-01-01
    • 2018-11-25
    • 2020-05-28
    • 2018-10-08
    • 1970-01-01
    • 2020-06-10
    • 2019-01-24
    • 1970-01-01
    相关资源
    最近更新 更多