angular - 如何从 firestore DocumentReference 数组字段创建可观察数组
问题描述
我正在构建一个用于电子商务目的的 Firestore 数据库。目前我有一个产品根级集合和一个用户根级集合。users 集合有一个名为 cart 的数组字段,我在其中存储了对该用户购物车中每个项目的 products 集合的 Documentreferences。我不确定Observable<Product[]>
从 DocumentReference 数组中正确形成一个的最佳方法。
我目前有一些这样的作品,但我很肯定这不是最好的方法,它会导致应用程序出现问题。特别是因为每次组件订阅此 observable 时,服务都会为购物车中的每个项目创建一个新订阅,并且这些订阅永远不会取消订阅......
// Current method from cart service
getItems(): Observable<Product[]> {
return this.auth.user.pipe(
map((user: User): Product[] => {
this.items = [];
user.cart.forEach((item: firestore.DocumentReference) => {
this.afs.doc(item.path).valueChanges().pipe(
map((product: Product) => {
this.items.push(product);
})
).subscribe();
});
return this.items;
})
);
}
我希望能够为登录用户查询此字段并Observalbe<Product[]>
从购物车服务返回一个,我可以订阅并使用它在组件中显示用户购物车中的项目。我对 rxjs 库的知识和理解相当初级,可能有一个操作员可以正确完成这项工作。提前感谢您的帮助!
解决方案
要取消订阅firestore
在您创建的 observable,请service
尝试以下操作
<!-- someName.component.ts -->
import {Subscription} from 'rxjs';
在您的组件类中
private firestoreSubscription: Subscription;
/* Your method to get data from firestore service */
getCartData(){
this.firestoreSubscription = this.service.getItems()
.subsribe(data=>//your stuff);
}
ngOnDestroy()
并在生命周期钩子中取消订阅Angular
ngOnDestroy(){
if (this.firestoreSubscription)
this.firestoreSubscription.unsubscribe();
}
推荐阅读
- c# - 循环语法中的 C# 错误
- google-bigquery - 如何从 BigQuery 导出到数据存储区?
- docker - Docker 容器中的 TurboVnc 服务器和其他容器中的 VirtualGL?
- reactjs - 400 上 axios 模型的 nock 不返回定义的值
- javascript - 如何在 django 中将提交按钮与 javascript 函数链接?
- sql-server - 我们什么时候应该关注磁盘 I/O?
- python - 从文件读取后获取特定元素
- spring-mvc - 获取基于 Spring Boot 的 Web 应用程序的请求 url
- python - 运行龙卷风应用程序时如何关闭终端?
- c++ - C++ 在 Linux 上使用 wstring_convert