【发布时间】:2021-05-23 16:05:44
【问题描述】:
我在我的 Angular 应用程序中使用 ng-bootstrap typeahead,并且希望仅在 typeahead 中搜索词的长度超过 3 个字符时才进行 API 调用以获取数据。我的组件中的代码是
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 调用,并确保返回空结果并且在 typeahead 中不显示任何内容如果搜索词的长度小于或等于 3 个字符,结果如何?请帮我解决这个问题。
【问题讨论】:
标签: angular rxjs ng-bootstrap typeahead