首页 > 解决方案 > Observable 导航返回后不会返回值

问题描述

我有一个我正在订阅的 observable。它工作正常,但是一旦导航然后再次返回,将不会显示任何数据。怎么会这样?

export class ProductOverviewComponent implements OnInit, OnDestroy {

  products;
  subscription;

  constructor(private data: CollectionService) { }

  ngOnInit(): void {
    this.subscription = this.data.products.subscribe(value => {
      console.log(value);
      this.products = value;
    });
  }

  ngOnDestroy(): void {
    this.subscription.unsubscribe();
  }

}
export class CollectionService {
  private productCollection: AngularFirestoreCollectionGroup<any>;

  products: Observable<any[]>;

  constructor(private db: AngularFirestore) {
    this.productCollection = db.collectionGroup('products');
    this.fetchProducts();
  }

  fetchProducts() {
    this.products = this.productCollection.snapshotChanges().pipe(
      map(actions => actions.map(a => {
        const data = a.payload.doc.data();
        const id = a.payload.doc.id;
        return { id, ...data };
      }))
    );
  }
}

标签: angulartypescriptrxjs

解决方案


您需要添加一个shareReplay,以便在订阅之间共享和重播数据:

fetchProducts() {
    this.products = this.productCollection.snapshotChanges().pipe(
      map(actions => actions.map(a => {
        const data = a.payload.doc.data();
        const id = a.payload.doc.id;
        return { id, ...data };
      })),
      shareReplay(1),
      // if you want to unsubscribe from source obs when there are no more subscribers
      // shareReplay({ refCount: true, bufferSize: 1 })
    );
  }

推荐阅读