Home > Mobile >  angular autocomplete suggestion list
angular autocomplete suggestion list

Time:03-08

I have an autocomplete function like this

chooseArtist: OperatorFunction<string, readonly string[]> = (text$: Observable<string>) =>
    text$.pipe(
      debounceTime(200),
      distinctUntilChanged(),
      map((term: any) => term.length < 2 ? []
        : this.artistlookuplist.filter((v: any) => v.name.toLowerCase().indexOf(term.toLowerCase()) > -1).slice(0, 10))
    )

And I have a service that populates the artistlookuplist like this:

getArtists(): void {
    this.artistService.getSearchArtist(this.searchstring).subscribe((data: any[]) => {
      this.artistlookuplist = data;
    });

I would like to combine these two. So that the list of autocomplete suggestion is only fetched when the chooseArtist function is called from the autocomplete field.

Any ideas how?

CodePudding user response:

I understand that you want to combine the two observables. When you need combine two observables, one depending from another you use switchMap rxjs operator

   import {of} from 'rxjs
   import {debounceTime,distictUntilChahne,switchMap} from 'rxjs/operators' 

   text$.pipe(
      debounceTime(200),
      distinctUntilChanged(),
      switchMap((term:any)=>{
          return term.length<2? of([]):
          this.artistService.getSearchArtist(term)
      })
    )

See that you have a first observable, the text$, and based in the value of "term" you return an observable (if term.length<2 use the of rxjs operator to return an objervable of an empty array, else the observable that return the service.

You can see switchMap as some like map. When we use map, we transform the response (but return an array or a string or...), when we use switchMap we "transform" the response return a new observable.

  • Related