javascript - 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()
似乎只是返回垃圾而不是实际文档。
解决方案
根本不知道如何进行这项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();
});
});
推荐阅读
- javascript - 我安装了错误的 NPM 包。我应该担心吗?
- mysql - 将 utf8mb4 转换为 latin1 时如何克服性能问题?
- reactjs - 为什么我的图表仍然显示 y 轴刻度的小数?
- python - Django:从基于类的视图中的函数保存模型实例不起作用
- c - 在我的递归函数中一遍又一遍地初始化我的变量
- r - 如何在 R 中合并来自多个 Excel 工作簿的多个工作表?
- sql - 为不同的值集过滤列
- javascript - React 渲染得到一个警告需要一个独特的“关键”道具
- excel - 在 VBA 中确定动态数据透视表的范围
- spring-boot - 在哪里可以找到 Jorge Acetozi 书“Java 应用程序的持续交付:Kubernetes 和 Jenkins 的实践”的更新源代码