1

I have 3 filter values (select boxes basically). When there is a selection change, I want to fire a combined API call along with other filter values selected previously (using BehaviorSubject for each filter). Unfortunately, in the 'combineLatest' I can see only 1 filter value. Other values from other subjects are disappearing. Please help me understand where am i going wrong:

Service:

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

Component -1 : from where 'next' is fired

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

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

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

component 2 - from where I am subscribing to the combined data

this.getData = this._appService.getData$
naveen
  • 53,448
  • 46
  • 161
  • 251
Kshri
  • 414
  • 3
  • 16
  • I guess that, once you subscribe to the combineLatest, it doesn’t fire again as there is no changing value anymore in comp2..? – MikeOne Aug 02 '21 at 17:59
  • I was calling the same function for every filter change :) And I think the behavior you are talking about is for forkJoin. combineLatest has to fire for every change in any observable – Kshri Aug 02 '21 at 18:02

1 Answers1

0

Got it,

Just had to make change in component 1, I was calling the "updateTypeFilter" for all filters. Lol.

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

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

  onPriceChanged() {
    this._appService.updatePriceFilter(this.priceSlected)
  }
Kshri
  • 414
  • 3
  • 16