2
votes

In an Angular app, I'm looking for an operator / a way to build an observable with rxjs but I don't understand how to do this.

What I need is a (rather simple) filter feature, but I couldn't make it work.

Source 1 is an array. Source 2 is a textbox (for filtering the array).

this.source1 = of (['abc', 'aef', 'ahi', 'jkl', 'xyz']);
this.filterBox = new FormControl();

combineLatest(
      source1,
      this.filterBox.valueChanges,
      (items, filter) => {
        console.log(items, filter);
        return items.filter(item => item.includes(filter));
      }
    ).subscribe(val => console.log(val));

This should output the whole array at the beginning, when filterBox is empty and hence not emitting anything.

I tried combineLatest, but the documentation says :

so long as each of the source Observables has emitted at least one item

Same with withLatestFrom.

What operator should be used here ?

1
try to use spread operator ...source1 into combineLatestShohel

1 Answers

4
votes

you can use startWith operator to give the observable an initial value. something like:

combineLatest(
 source1,
 this.filterBox.valueChanges.pipe(startWith("")),
 (items, filter) => {
  console.log(items, filter);
  return items.filter(item => item.includes(filter));
 }
).subscribe(val => console.log(val));

Learn more from here https://coryrylan.com/blog/subscribing-to-multiple-observables-in-angular-components