如何解决根据 ng-bootstrap 的 typeahead 中的条件使用 switchMap 进行 API 调用
我在我的 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 个字符,结果如何?请帮我解决这个问题。
解决方法
你可以在你的 switchMap 中做一个条件。 像这样:
distinctUntilChanged(),switchMap((searchText) => searchText.length > 3 ? this.carsService.getCars(searchText) : of({cars:[]});
您可以从 rxjs 导入 of
。
您可以向流中添加 filter 运算符
return text$.pipe(
debounceTime(200),distinctUntilChanged(),filter(val => val.length >= 3),switchMap((searchText) => {
return this.carsService.getCars(searchText);
}) .....
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。