【问题标题】:Angular Firebase Firestore get document IDAngular Firebase Firestore 获取文档 ID
【发布时间】:2018-07-23 01:22:44
【问题描述】:

我的 Firebase Firestore 数据库是这样的:

Collection:orders
    DocumentID: (autogenerated)
         Document: orderName: string

变量声明如下:

    orderCollection: AngularFirestoreCollection<Order>
    orders: Observable<Order[]>

我收到所有这样的“订单”:

orderCollection = this.afs.collection('orders');
orders = this.orderCollection.valueChanges();

然后我打印这样的订单:

<tr *ngFor="let o of orders | async">
    <td>{{o.orderName}}</td>
    <td><a (click)="editOrder(o.$key)">Edit</a></td>
</tr>

到编辑部分为止,我的一切工作都很完美。

对于编辑:我如何发回订单的文档 ID?我想发回订单文档 ID,以便随后进行编辑。使用实时数据库,您可以使用 $key 执行某些操作,但不能使用 firestore。有什么建议吗?

【问题讨论】:

    标签: firebase google-cloud-firestore angularfire2


    【解决方案1】:

    在 AngularFirestore 中,它只是 document.id。但要使其正常工作,您必须使用snapshotChanges 而不是valueChanges。所以:

    orders = this.orderCollection.snapshotChanges();
    

    然后:

    <tr *ngFor="let o of orders | async">
        <td>{{o.data().orderName}}</td>
        <td><a (click)="editOrder(o.id)">Edit</a></td>
    </tr>
    

    灵感来自:Firestore Getting documents id from collectionGet Collections with Document Ids Included

    【讨论】:

    • 我的变量声明如下:

      orderCollection: AngularFirestoreCollection
      orders: Observable

      this.orderCollection = this .afs.collection('orders');
      this.orders = this.orderCollection.snapshotChanges();

      但是使用 snapshotChanges(),我在 this.orders 上收到错误:
      type 'Observable[]>' 不可分配给类型 'Observable'。
      有什么想法吗?
    【解决方案2】:

    导入这个

    import { map } from 'rxjs/operators';
    

    并确保在您的界面中包含 id

    export interface Order{
      id?:string
      foo1?: string
      foo2?: string
      foo3?: string
    }
    

    你的函数看起来像这样

    this.orderCollection = this.afs.collection<Order>('orders');
     this.orders = this.orderCollection.snapshotChanges().pipe(
          map(kazi => {
          return kazi.map(a => {
              const data = a.payload.doc.data();
              const id = a.payload.doc.id;
    
              return { id, ...data };
          });
          })
      );
    

    得到结果

      this.orders.forEach(order =>{
          console.log(order)   
    })
    

    希望对你有帮助

    【讨论】:

      猜你喜欢
      • 2019-11-15
      • 2020-04-22
      • 2018-09-03
      • 1970-01-01
      • 2021-07-20
      • 1970-01-01
      • 2019-07-04
      • 2020-03-09
      • 1970-01-01
      相关资源
      最近更新 更多