问题描述
使用AngularFire2,我尝试从单个Firestore文档中获取数据. 有效的方法是:
Using AngularFire2 I try to get data from a single Firestore document. What works is:
this.addressRef = afs.doc<Address>('addresses/key')
this.addressRef.valueChanges().subscribe(val => {......}
我只想运行一次订阅代码.通常,我使用take(1)实现此目的(与Firebase DB一起使用). 但是此代码:
I want to run the subscription code just once. Normally I use take(1) to achieve this (works with the Firebase DB). But this code:
this.addressRef.valueChanges().take(1).subscribe(val => {......}
给出错误:TypeError:this.addressRef.valueChanges(...).take不是函数.
gives error: TypeError: this.addressRef.valueChanges(...).take is not a function.
VS Code列出了执行动作.这是AngularFire2中的bug,是我做错了还是获取数据后停止订阅的另一种(更好)方式?我也尝试了topromise,但这也失败了.
VS Code is listing the take action. Is this a bug in AngularFire2, am I doing this wrong or is there an other (better) way to stop the subscription after the data is fetched? I also tried topromise but this also failed.
推荐答案
更新
由于此答案已引起广泛关注,因此我提供了更新的答案.通常,您应该在使用可观察变量进行编程时尝试做出反应.有一些很棒的教程,但是这是很好的
Because this answer has received a lot of attention, I have provided an updated answer. You should, in general, try to think reactively when programming with observables. There are some great tutorials, but this one is good.
新解决方案
user$ = this.afDs.doc<User>('users/NaGjauNy3vYOzp759xsc')
.valueChanges().pipe(
take(1) // Here you can limit to only emit once, using the take operator
)
在模板中,您订阅了可观察对象.
And in your template, you subscribe to your observable.
{{(user$ | async).name}}
上下文
这种解决问题的方法有很多好处:
This way of solving the problem has multiple benefits:
- 如果您不希望转换数据,只需抛出一个地图运算符
- 您可以使用rxjs过滤器运算符过滤事件
- 基于用户$流创建其他流
- 易于调试,因为其他开发人员可以更透明的方式查看应用程序中的数据流
例如(创建另一个流,该流仅在用户为admin时发出,并创建一个新标题):
For example (creating another stream, that only emits if the user is admin, and creates a new title):
adminTitle$ = this.user$.pipe(
filter(user => user.title === 'admin'),
map(user => `${user.name} (admin)`)
)
旧答案
您可以通过执行以下操作来实现:
You can achieve this by doing the following:
this.userDoc = afDs.doc<User>('users/NaGjauNy3vYOzp759xsc');
this.userDoc.valueChanges()
.pipe(take(1))
.subscribe(v => {
this.user = v;
});
这篇关于AngularFire2 Firestore Take(1)对文档值的更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!