根据 ng-bootstrap 的提前输入条件使用 switchMap 进行 API 调用

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

我在我的 Angular 应用程序中使用 ng-bootstrap typeahead 并且想要进行 API 调用以仅当 typeahead 中的搜索词长度更长时才获取数据超过 3 个字符。我组件中的代码是

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)              
  );                 
 }

服务文件中调用API的代码是

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

如何修改组件内的代码以确保仅当用户输入的搜索词长度超过 3 个字符时才调用 API 并确保返回空结果如果搜索词的长度小于或等于 3 个字符,则预输入结果中不会显示任何内容?请帮我解决这个问题。

你可以在你的 switchMap 中做一个条件。 像这样:

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

您可以从 rxjs 导入 of

of

您可以将 filter 运算符添加到您的流中

  return text$.pipe(      
      debounceTime(200), 
      distinctUntilChanged(),
     filter(val => val.length >= 3),
      switchMap((searchText) => {
          return this.carsService.getCars(searchText);
      }) .....