How to get typeahead suggestions with API

Viewed 465

Trying to get names as ng-typeahead suggestions and tried below code but unable to get the autosuggestions. Here is my code.

fnPopulateEntity1Lovs() {
  this.http
    .get("https://reqres.in/api/products/", {})
    .subscribe((res) => {
      this.testData = res;
    });
}

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

Demo: StackBlitz
Could you please suggest me how to get the typeahead options?

1 Answers

HTML

<input id="typeahead-http" type="text" 
  class="form-control mx-sm-3" 
  [class.is-invalid]="searchFailed" 
  [(ngModel)]="model" 
  [ngbTypeahead]="search" 
  [inputFormatter]="formatter"
  [resultFormatter]="formatter"
  placeholder="Product search" />

Service: Create a service Product Service

@Injectable(
  {
    providedIn: 'root'
  }
)
export class ProductService {
  constructor(private http: HttpClient) {}

  search(term: string) {
    if (term === '') {
      return of([]);
    }

    return this.http.get<any>(PRODUCTS_URL).pipe(
        map(response => response.data), //since the response is wrapped in a data object
        tap(res => console.log({res}))
      );
  }
}

Now call search in the component like this

search: OperatorFunction<string, readonly string[]> = (text$: Observable<string>) =>
  text$.pipe(
    debounceTime(300),
    distinctUntilChanged(),
    tap(() => this.searching = true),
    switchMap(term =>
      this._service.search(term).pipe(
        tap(() => this.searchFailed = false),
        catchError(() => {
          this.searchFailed = true;
          return of([]);
        }))
    ),
    tap(() => this.searching = false)
  );

Use a result formatter

formatter = (x: {name: string}) => x.name;

Demo: StackBlitz Project

Related