0

I'm using ng-select custom server-side search to load data based on what the user types. Currently it only works if a keyword is actually pressed. I'd like to trigger the http request each time the dropdown is opened, even if the search term is empty

component.html

<ng-select [items]="filterValues$ | async"
    [typeahead]="filterValuesInput$"
    [multiple]="true"
    (open)="getFilterValues(pref.id)"
    [loading]="filterValuesLoading"
    bindLabel="name"
    [(ngModel)]="filter_values">
</ng-select>

component.ts

getFilterValues(filterId) {
    this.filterValues$ = concat(
      of([]), // default items
      this.filterValuesInput$.pipe(
        distinctUntilChanged(),
        tap(() => this.filterValuesLoading = true),
        switchMap(term => this.service.getFilterValues(filterName, '' + term).pipe(
          map(res => res.filter_values),
          catchError(() => of([])), // empty list on error
          tap(() => this.filterValuesLoading = false)
        ))
      )
    );
}

I'm trying to understand how switchMap() triggers the request only after an input value is typed. How do I make it trigger the service's method each time the getFilterValues method is called?

shAkur
  • 944
  • 2
  • 21
  • 45

1 Answers1

0

switchMap() triggers the request only after an input value is typed.

I think the distinctUntilChanged function is the culprit.

according to docs switchMap() only cancels previous obervables.

Take a look at the example, when i commented out distinctUntilChanged select input outputted values regardless of previous state.

const subject = new rxjs.Subject();

const obs = subject.pipe(
  //rxjs.operators.distinctUntilChanged(),
  rxjs.operators.switchMap(value =>
    rxjs.of("apples", "bananas", "oranges").pipe(
      rxjs.operators.filter(pr => pr.includes(value))
    )
  )
);

const subscription = obs.subscribe(value => {
  console.log(value);
});

var selectEl = document.getElementById("select");
selectEl.addEventListener("click", filter);
selectEl.addEventListener("change", filter);

function filter(event) {
  subject.next(event.target.value)
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/6.5.5/rxjs.umd.js"></script>
<select id="select">
  <option>a</option>
  <option>b</option>
</select>
Józef Podlecki
  • 10,453
  • 5
  • 24
  • 50