简体   繁体   English

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

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

How to make it work okay?如何让它正常工作? I need only one document from base with id.Is it possible to subscribe it?我只需要一个带有 id 的 base 文档。可以订阅它吗? Because it returns me a Observable object:(因为它返回给我一个 Observable 对象:(

Here`s my code.这是我的代码。

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

I think you are trying to do this:我认为您正在尝试这样做:

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

The above is the simplest way I know to read a document on firestore.以上是我所知道的在 firestore 上阅读文档的最简单方法。 It will show the internal data from your document.它将显示您文档中的内部数据。 I hope it helps to you.我希望它对你有帮助。

Let's try to convert the observable to promise like this让我们尝试将 observable 转换为这样的 promise

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

First thing first, you should make sure that your id is right.首先,你应该确保你的ID是正确的。 And I assume you used AngularFirestore to connect to Firebase.我假设您使用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}
                });
   }

If you also want the id of the document and use an observable instead, do:如果您还想要文档的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