AngularFire 集合:Update/replace 具有新路径的查询路径

AngularFire collection: Update/replace query path with a new path

我有一个具有 AngularFirestore.collection Observable 的服务。

...
export class AppFirestoreService {
  public rootCategories$: Observable<Category[]>;

  constructor(private afs: AngularFirestore) {
    this.rootCategories$ = this.afs.collection<Category>(`categories`).snapshotChanges()
    .pip(
      ...
    );
  }
}

问题是 rootCategories$ 在几个组件中被 订阅 ,而 path 我需要更新到另一个组件.

所以我想 用新的 Observable 替换 rootCategories 变量,但我不确定旧的 Observable将被清除内存。 有没有一种方法可以将路径作为变量而不创建另一个 Observable 并将旧路径(或其订阅)留在内存中。 谢谢

你能指导我解决这个问题的正确方法吗?

编辑澄清: 如何使用新路径更改当前 Observable rootCategories$,并使用新发出的值通知旧订阅?

我找到了一个解决方案,除非有人指出它有一些缺点。

BehaviorSubject和mergeMap的结合,解决了我的问题。该路径由 BehaviorSubject 发出并控制,并且 AngularFirestore.collection 与新路径一起返回:

import { Injectable } from '@angular/core';
import { AngularFirestore } from '@angular/fire/firestore'
import { Observable, BehaviorSubject } from 'rxjs';
import { mergeMap } from 'rxjs/operators';
...
@Injectable(...)
export class AppFirestoreService {
  public rootCategories$: Observable<CategoryId[]>;
  private pathBS = new BehaviorSubject<string>('categories');

  constructor(private afs: AngularFirestore) {
    this.rootCategories$ = this.pathBS.asObservable().pipe(
      mergeMap(path => {
        return this.afs.collection<Category>(path).snapshotChanges()...
      })
    );
  }

  setNewPath(path: string) {
    this.pathBS.next(path);
  }
}