繁体   English   中英

如何通过 ID Angular 4 + Firestore 获取一份文档

[英]How to get one document by ID Angular 4 + Firestore

如何让它正常工作? 我只需要一个带有 id 的 base 文档。可以订阅它吗? 因为它返回给我一个 Observable 对象:(

这是我的代码。

getByid(id){
  return this.itemscollection.doc('9K6ue-afwwafwaf').valueChanges();
  }

我认为您正在尝试这样做:

constructor(db: AngularFirestore){
db.collection('yourcollection').doc("documentid").ref.get().then(function (doc) {
  if (doc.exists) {
    console.log(doc.data());
  } else {
    console.log("There is no document!");
  }
}).catch(function (error) {
  console.log("There was an error getting your document:", error);
});}

以上是我所知道的在 firestore 上阅读文档的最简单方法。 它将显示您文档中的内部数据。 我希望它对你有帮助。

让我们尝试将 observable 转换为这样的 promise

  async getDocument(docId:string){
    let document = await this.afs.doc(docId).get().toPromise();
    return document.data();
  }

首先,你应该确保你的ID是正确的。 我假设您使用AngularFirestore连接到 Firebase。

   public this.itemsCollection = null;
   public constructor(private af: AngularFirestore) {
     this.itemCollection = this.af.collection('Your-colection-name');
   }

   public getById(docId: string): any {
     return this.itemCollection
                .doc(docId)
                .valueChanges()
                .subscribe(item => {
                  return item; 
                  // If you prefer including itemId back to object
                  // return {...item, id: docId}
                });
   }

如果您还想要文档的id并使用 observable 代替,请执行以下操作:

this.firestore.collection('collection').doc('someid').snapshotChanges().subscribe(
      res => {
        this.item= { id: res.payload.id, ...res.payload.data() as InterfaceName };
      },
      err => {
        console.debug(err);
      }
    )

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM