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

Query firestore collection once and use document data

我有这个功能可以通过 firestore 集合并将文档数据 return 放入 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.
      })

  }

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

来自@davideast