首页 > 解决方案 > 如何从 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 库的知识和理解相当初级,可能有一个操作员可以正确完成这项工作。提前感谢您的帮助!

标签: angularrxjsgoogle-cloud-firestoreangularfire

解决方案


要取消订阅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();
}

推荐阅读