angularangular6typeaheadbootstrap-typeahead

In Typeahead, unable to subscribe to service to get data to bind to typeahead search


i'm using ngbootstrap typeahead (https://ng-bootstrap.github.io/#/components/typeahead/examples#http)

as per example mentioned we need to return observable to [ngbTypeahead]="search"

we're expecting below result from API

{ "data": { "groupNames": [ "group level one", "group level two", "group level one", "group level two" ] } }

from this return result we need to filter by containing word.

search = (text$: Observable<string>) => text$.pipe( debounceTime(300), distinctUntilChanged(), map((term) => term.length < 1 ? [] : this.productService.getGroups().subscribe((response) => { if (response && response.data) { return response.data.groupNames.filter((response) => response.toLowerCase().indexOf(term.toLowerCase()) > -1); } }, ), ), )

Question :

how do i return below result as observable to typahead property

return response.data.groupNames.filter((response) => response.toLowerCase().indexOf(term.toLowerCase()) > -1);

( note - we're fetching whole data from service and from result we're doing filter result as per user type)


Solution

  • returning from a subscription callback makes almost no sense. You could try to replace subscribe with switchMap and return events from a stream, rather than trying to return events in subscription. I guess working example would look like:

    search = (text$: Observable<string>) =>
        text$.pipe(
          debounceTime(300),
          distinctUntilChanged(),
          switchMap((term) => term.length < 1 ? of([]) :
            this.productService.getGroups().pipe(
              filter((response) => response && response.data)
              map((response) => response.data.groupNames.filter((response) => response.toLowerCase().indexOf(term.toLowerCase()) > -1))
            )
          ),
        )