使用angularfire2获取单个文档的最简单方法
Simplest way to get a single document with angularfire2
我正在尝试使用基本表单以便更新数据。
我可以查询一个完整的集合(并且可以选择在客户端过滤我需要的数据,如果它还不适合我的话)。
知道id就可以查询单个文档。
但是我想查询一个带有业务标准的集合,并能够将它添加到我的视图中(当然还有一种方法可以在表单更新时更新数据。)
其实我的问题好像很接近
但是:
获取所有数据并过滤它在我看来是一个糟糕的解决方案
我试过了,但我不确定是否理解 allPayments 和 payment 的含义(类型)(为此我猜这是一项业务 class 如果是这样,好吧)这个给定的例子:
getPaymentByBookingId(id: string): Observable<Payment> {
return this.afs.collection<Payment>('payments')
.valueChanges()
.pipe(
map(allPayments=>allPayments.find(payment=>payment.bookingId === id))
);
}
我刚拿到一个
Cannot read property '<my_attribute' of undefined
假设 get 返回 null。
正如您所建议的,在客户端进行过滤并不是执行此操作的理想方式。您需要在 bookingId
上查询集合,然后 limit()
得到一个结果。
这仍然是 return 一个包含一项的数组 (limit(1)
),但您可以使用 flatMap()
将结果展平以获得单个 Payment
:
getPaymentByBookingId(id: string): Observable<Payment> {
return this.afs
.collection<Payment>('payments', ref => ref.where('bookingId', '==', id).limit(1))
.valueChanges()
.pipe(
flatMap(payments => payments)
);
}
我正在尝试使用基本表单以便更新数据。 我可以查询一个完整的集合(并且可以选择在客户端过滤我需要的数据,如果它还不适合我的话)。
知道id就可以查询单个文档。 但是我想查询一个带有业务标准的集合,并能够将它添加到我的视图中(当然还有一种方法可以在表单更新时更新数据。)
其实我的问题好像很接近
获取所有数据并过滤它在我看来是一个糟糕的解决方案
我试过了,但我不确定是否理解 allPayments 和 payment 的含义(类型)(为此我猜这是一项业务 class 如果是这样,好吧)这个给定的例子:
getPaymentByBookingId(id: string): Observable<Payment> { return this.afs.collection<Payment>('payments') .valueChanges() .pipe( map(allPayments=>allPayments.find(payment=>payment.bookingId === id)) ); }
我刚拿到一个
Cannot read property '<my_attribute' of undefined
假设 get 返回 null。
正如您所建议的,在客户端进行过滤并不是执行此操作的理想方式。您需要在 bookingId
上查询集合,然后 limit()
得到一个结果。
这仍然是 return 一个包含一项的数组 (limit(1)
),但您可以使用 flatMap()
将结果展平以获得单个 Payment
:
getPaymentByBookingId(id: string): Observable<Payment> {
return this.afs
.collection<Payment>('payments', ref => ref.where('bookingId', '==', id).limit(1))
.valueChanges()
.pipe(
flatMap(payments => payments)
);
}