如何以角度访问Firestore集合中的文档字段?

时间:2020-07-21 08:20:31

标签: angular typescript firebase google-cloud-firestore

我试图基于ID访问用户的photoUrl,但不幸的是不值得戴帽子。

我已附上我的Firestore收藏夹的图片,请告诉我如何访问photoUrl。 User is the main collection, document on the basis of ID are document and each document have some fielld I want to access photourl on the basis of ID. 用户是主要的收藏,基于ID的文档是文档,每个文档都有一些我想基于ID访问photourl的地方。

getImage(id) { this.users=this.db.collection('user').doc(id).collection('photurl').valueChanges(); console.log(this.users); }

我已经在答案中实现了代码,但是面对一个新问题,由于结果图片未显示,该函数不断自我调用。

<div *ngFor="let Question of Questions "> <img src="{{ getImage(Question.authorNo) }}" class="d-block ui-w-40 rounded-circle" alt="">

这是我的html,我使用了迭代器,因为我有很多问题,我正在获取作者的authorID并将其与用户ID匹配,如果有任何用户ID与AuthorID匹配,则将其获取photoUrl并显示它 我获取photoUrl的功能如下

getImage(id) { this.db.doc( user / $ {id}`).valueChanges()。subscribe(user => { this.user =用户; this.url = this.user.photoUrl; //console.log(this.url);

}); 返回this.url; }`

1 个答案:

答案 0 :(得分:2)

使用Observable订阅用户数据并将photoUrl分配给变量[选项1],或者然后可以将所有用户数据分配给用户变量并在模板[选项中使用user.photoUrl 2]。

选项1

user: any;
photoUrl: string; 

...

ngOnInit(): void {
    this.db.doc(`user/${id}`).valueChanges().subscribe(user => {
        this.user = user;
        this.photoUrl = user.photoUrl;
    });
}

选项2

user: any; 

...

ngOnInit(): void {
    this.db.doc(`user/${id}`).valueChanges().subscribe(user => this.user = user);
}

编辑:您当前使用的数据模型无法提供简单的选项来检索照片网址。建议像处理作者ID一样,将照片网址直接保存到问题文档中,以防止出现过多的阅读次数。选项3可以让您做自己想做的事,但不建议这样做。

不建议使用选项3

photoData = [];

...

ngOnInit(): void {
    this.db.collection<any>('user').snapshotChanges().subscribe(snapshots => {
      snapshots.forEach(snapshot => {
        const url = snapshot.payload.doc.data().photoUrl;
        const id = snapshot.payload.doc.id;
        const data = { url, id };
        this.photoData.push(data);
      })
    });
}


getImage(id: string) {
  this.photoData.forEach(item => {
    if (item.id === id) {
      return item.url;
    }
  })
}