一次查询firestore集合并使用文档数据

时间:2018-06-06 19:48:55

标签: javascript firebase google-cloud-firestore angularfire2

我有这个函数来遍历firestore集合并将文档数据返回到Observable。然后使用observable我想遍历文档并将这些文档添加到firestore中的另一个集合中。

由于某种原因,每次此集合提供更改时,都会调用此方法。我只希望从特定组件调用一次。任何帮助将不胜感激。

addProductsToOrder(){

 this.myCartProducts = this.afs.collection(`/users/DfyEg7WwnPsz73ln0Ptd/mycart/l4c2QOQ4rb8sivOtXkSb/products`)
      .snapshotChanges().pipe(map(actions=>{
        return actions.map(a=>{
          const data = a.payload.doc.data();
          const id = a.payload.doc.id;

          return data;
        })
      }));


      //i have tried subscribe as well as forEach
      this.myCartProducts.forEach(val =>{
        console.log(val)
        //over here i'll add code to add this val into another firebase collection.
      })

  }

1 个答案:

答案 0 :(得分:0)

FB本身不支持.get()方法,但你有两个选择。

使用基础参考

constructor(afs: AngularFirestore) {
 afs.collection('items').ref.get();
 }

使用.take(1)

// import { take } from 'rxjs/operators';
constructor(afs: AngularFirestore) {
  afs.collection('items').valueChanges().pipe(take(1));
}

by @davideast