如何从Firestore获取当前用户数据?

问题描述 投票:0回答:1

我正在Ionic 4项目上工作,我想在其中显示用户登录应用程序后当前用户的所有帖子。目前,我正在使用snapshotChanges()subscribe()方法(如下所示)从firestore中获取数据。但是它为我提供了来自Firestore文档的每个数据。在两个文档中都有userIDpostID引用时,如何从该特定用户那里获取authordesc的值,或者有可能吗?具体来说,如何显示用户(6YbhQux2sgTH66F0cJpdcT87Pw83)的帖子(54d039ec-5b3c-4ee9-95a0-418b06365f25),其中包含authordesc

Firestore:firestore image

这是我所做的:

getData.service.ts

readData() {
  return this.firestore.collection('posts').snapshotChanges();   
}

post.ts

this.getData.readData().subscribe(data => {

  this.posts = data.map(e => {

    return {
      id: e.payload.doc.id,
      Author: e.payload.doc.data()['author'],
      Description: e.payload.doc.data()['desc'],
    };

  })
  console.log(this.posts);
});

post.html

<ion-card no-padding *ngFor="let post of posts">
    <ion-card-header>
      <ion-card-title>{{post.Author}}</ion-card-title>
    </ion-card-header>
    <ion-card-content>
      <p>{{ post.Description }}</p>
    </ion-card-content>
</ion-card>

我也尝试使用afAuth.auth.currentUser获取当前用户ID和帖子,但显示错误Property 'map' does not exist on type 'DocumentSnapshot'。我对此并不陌生,不确定如何进行。

let user = this.afAuth.auth.currentUser;
uid = user.uid;

this.afs.firestore.collection('users').doc(uid).get()
    .then(doc=>{
       var a = doc.data().posts
       console.log(a);
       this.afs.firestore.collection('posts').doc()
       .get().then(doc2=>{
         this.promotions = doc2.map(e=>{
           return {
             id: e.payload.doc2.id,
             Author: e.payload.doc2.data()['author'],
             Description: e.payload.doc2.data()['desc'],
           };
         })
     })
  })
javascript typescript firebase ionic-framework google-cloud-firestore
1个回答
0
投票

要获取authordesc,请尝试以下操作:

let user = this.afAuth.auth.currentUser;
uid = user.uid;

const docs = this.afs.firestore.collection('users').doc(uid);
    const userInfo = docs.snapshotChanges().pipe(
      map(data => {
        return {
          id: data.payload.doc.id,
          Author: data.payload.doc.data()['author']
          Description: data.payload.doc.data()['desc']
        };
      }));

[似乎您正在使用angularfire,首先将引用放在文档angularfire上,然后使用userid,它返回snapshotChanges,然后可以检索数据。 ObservablePipe类中的一个实例方法,用于将功能运算符缝合在一起(Pipe是这些运算符之一)。

© www.soinside.com 2019 - 2024. All rights reserved.