首页 > 解决方案 > Angularfire2在没有监听器的情况下获取单个文档

问题描述

我正在使用 angularfire2 v6 和 angular 11。我只是想根据用户的电子邮件从用户集合中获取单个文档。我不想使用valueChanges()或者snapshotChanges()因为用户对象不会被更新,如果是,我不在乎获得实时更新。我只想在用户导航到他们的个人资料时获取一次数据。我已经看到您应该能够使用get()而不是上述方法,但我无法让任何东西正常工作。

这样做很好:

let query = (this.firestore.collection('users', ref => ref.where('email', '==', res.email)).valueChanges());
// subscribe to changes
query.subscribe(queriedItems => {
  this.item = queriedItems[0];
  this.firstName = this.item.firstname;
  this.lastName = this.item.lastname;
  this.email = this.item.email;
  this.role = this.item.role;
  this.lead = !!this.item.lead;
});

但同样,不是valueChanges()天生就一直在听更新吗?我不想那样做。替换.valueChanges().get()意味着我无法订阅,并且 usingtoPromise().then()似乎只是返回垃圾而不是实际文档。

标签: javascriptangularfirebasegoogle-cloud-firestoreangularfire2

解决方案


根本不知道如何进行这项get()工作,但我确实找到了一种解决方法,方法是将其设置为订阅,然后在获得数据后取消订阅。

this.fireAuth.currentUser.then((res) => {

  let query = (this.firestore.collection('users', ref => ref.where('email', '==', res.email)).valueChanges());
  // subscribe to changes
  this.profileSubscription = query.subscribe(queriedItems => {
    this.item = queriedItems[0];
    this.firstName = this.item.firstname;
    this.lastName = this.item.lastname;
    this.email = this.item.email;
    this.role = this.item.role;
    this.lead = !!this.item.lead;

    //Unsubscribe here if you don't want an active listener to show changes
    this.profileSubscription.unsubscribe();
  });

});

推荐阅读