【问题标题】:AngularFire collection: Update/replace query path with a new pathAngularFire 集合:用新路径更新/替换查询路径
【发布时间】:2020-03-27 12:30:20
【问题描述】:

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

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

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

问题在于rootCategories$ 在多个组件中订阅,而我需要更新到另一个组件的路径

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

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

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

【问题讨论】:

  • 所以你想分享 rootCategories$?
  • @FanCheung 它已经共享,但我想使用其他路径更改来自 Observable 的结果。
  • 您可以使用 rootCategories 来为此目的组成一个新的流,而不影响现有的订阅。 myNewStream=$this.rootCategories$.pipe(.....)
  • 或者您是否希望动态更改收集路径?
  • 将其设置为函数rootCategories=(path)=&gt;this.afs.collection(path).snapshotChanges()

标签: angular rxjs angularfire2


【解决方案1】:

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

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);
  }
}

【讨论】:

    猜你喜欢
    • 2017-01-04
    • 2021-08-12
    • 2021-11-05
    • 2015-02-13
    • 2012-03-28
    • 2011-12-22
    • 2021-02-27
    • 2018-12-01
    • 1970-01-01
    相关资源
    最近更新 更多