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