【问题标题】:RxJS combineLatest: Unable to merge with latest values in Angular 12RxJS combineLatest:无法与 Angular 12 中的最新值合并
【发布时间】:2021-10-08 01:12:14
【问题描述】:

我有 3 个过滤器值(基本上是选择框)。当有选择变化时,我想宣传组合的API呼叫以及先前选择的其他过滤器值(使用每个过滤器的行为库)。不幸的是,在“combineLatest”中,我只能看到 1 个过滤器值。来自其他主题的其他价值正在消失。请帮助我了解我哪里出错了:

服务:

private typeFilterSubject = new BehaviorSubject('');
typeFilterObs$ = this.typeFilterSubject.asObservable();

private priceFilterSubject = new BehaviorSubject('');
priceFilterObs$ = this.priceFilterSubject.asObservable();

private brandFilterSubject = new BehaviorSubject('');
brandFilterObs$ = this.brandFilterSubject.asObservable();

updateTypeFilter(filter) {
  this.typeFilterSubject.next(filter);
}
updatePriceFilter(filter) {
  this.priceFilterSubject.next(filter);
}
updateBrandFilter(filter) {
  this.brandFilterSubject.next(filter);
}

getData$ = combineLatest([
  this.typeFilterObs$,
  this.priceFilterObs$,
  this.brandFilterObs$
]).pipe(
  switchMap(([type, price,brand]) => {
    console.log([type, price, brand]);

    // here i am getting ["electronics","",""]
    // or [14, "", ""] or ["IKEA", "", ""]
    // instead of ["electronics", 14, "IKEA"]

    return this._http.get<IProduct[]>(
      `http://localhost:3000/products?type=${type}&price=${price}&brand=${brand}`
    );
  })
);

组件 -1:'next' 从哪里触发

onTypeChanged() {
  this._appService.updateTypeFilter(this.typeSelected) //"Electronics"
}

onBrandChanged() {
  this._appService.updateTypeFilter(this.brandSelected) //"IKEA"
} 

onPriceChanged() {
  this._appService.updateTypeFilter(this.priceSlected) //14
}

组件 2 - 我订阅组合数据的位置

this.getData = this._appService.getData$

【问题讨论】:

  • 我猜,一旦你订阅了 combineLatest,它就不会再次触发,因为 comp2 中的值不再变化......?
  • 我为每个过滤器更改调用相同的函数 :) 我认为你正在谈论的行为是 forkJoin。 combineLatest 必须为任何可观察到的每一个变化触发

标签: angular rxjs angular2-observables rxjs-observables rxjs-pipeable-operators


【解决方案1】:

知道了,

只需要在组件 1 中进行更改,我正在为所有过滤器调用“updateTypeFilter”。哈哈。

 onTypeChanged() {
    this._appService.updateTypeFilter(this.typeSelected)
  }

  onBrandChanged() {
    this._appService.updateBrandFilter(this.brandSelected)
  }

  onPriceChanged() {
    this._appService.updatePriceFilter(this.priceSlected)
  }

【讨论】:

    猜你喜欢
    • 2019-05-12
    • 2019-08-25
    • 1970-01-01
    • 1970-01-01
    • 2017-06-25
    • 2020-06-24
    • 2022-01-24
    • 1970-01-01
    • 2018-09-29
    相关资源
    最近更新 更多