Angularfire2 AngularFirestoreCollection不向集合

时间:2017-10-13 17:36:02

标签: javascript angular firebase google-cloud-firestore

我试图在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如何将文档发送回集合中?

1 个答案:

答案 0 :(得分:4)

.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};
  });
});

这应该会为您提供所需的数据