Search code examples
angularrxjsng-bootstraptypeahead

Make an API call using switchMap based on a condition in typeahead of ng-bootstrap


I am using ng-bootstrap typeahead in my Angular app and want to make an API call to fetch data only if length of the search term in the typeahead is more than 3 characters. The code in my component is

search = (text$: Observable<string>) => {
  return text$.pipe(      
      debounceTime(200), 
      distinctUntilChanged(),
      switchMap((searchText) => {
          return this.carsService.getCars(searchText);
      }),
      map(response => {
          return response.cars.map((item: any) => {
            if(item.name === "Porsche") {
              item.name += " - Luxury car";
            }
            else {
              item.name += " - Normal car";
            }
            return item;
          });
      }),
      catchError(error => error)              
  );                 
 }

The code in the service file to call the API is

getCars(searchText: string): Observable<any> {
  return this.http.get(`${environment.baseUrl}/cars?searchTerm=${searchText}`).pipe(
     map((res: any) => res),
     catchError(error => throwError(error))
  );
}

How can I modify the code inside the component to ensure that the API call is made only if the length of the search term entered by user is more than 3 characters and to ensure that empty results are returned and nothing is shown in typeahead results if length of the search term is less than or equal to 3 characters? Please help me out with this issue.


Solution

  • You could do a conditional inside your switchMap. Like so:

    distinctUntilChanged(), 
    switchMap((searchText) => searchText.length > 3 ? this.carsService.getCars(searchText) : of({cars:[]}); 
    

    You can import of from rxjs.

    of