Angularfire2 AngularFirestoreCollection 不发送集合中每个对象的键

Angularfire2 AngularFirestoreCollection not sending keys with each object in collection

我正在尝试在 Angular 4 应用程序中使用 Angularfire2。我可以使用 AngularFirestoreCollection 从我的 firestore 中获取对象集合。但是,当我遍历集合中的文档时,我注意到文档不包含文档键。所以,我认为我没有办法做从 UI 中的列表中删除文档之类的事情,因为我不知道与该文档关联的密钥。这是我的代码:

  export class CategoryComponent implements OnInit {
      private categoryCollection: AngularFirestoreCollection<any>;
      public categories: Observable<any[]>;
      public category: Category;

      constructor(public db: AngularFirestore, private router: Router) {
          this.categoryCollection = db.collection<any>('categories');
          this.categories = this.categoryCollection.valueChanges();
          this.category = new Category();
      } 
 }

该代码为我提供了一个如下所示的集合:

{name: 'Some name'}

我期望的是:

{key: 'theKey', name: 'Some name'}

我一直在看 github 上的文档,但我要么是盲人,要么文档没有显示我做错了什么。也许我只是不知道 firebase 如何将文档发回集合中?

.valueChanges()方法只会给你数据。如果您也需要密钥,可以使用 .snapshotChanges()

.map((actions: any) => {
    return actions.map(action => {
      const data = action.payload.doc.data();
      const key = action.payload.doc.id;
      return {key, ...data};
    });
  });

为了也添加文档密钥
在您的上下文中可能看起来像这样

this.categories = this.categoryCollection.snapshotChanges().map((actions: any) => {
  return actions.map(action => {
    const data = action.payload.doc.data();
    const key = action.payload.doc.id;
    return {key, ...data};
  });
});

这应该会给你想要的数据