如何解决Angular typeahead debouncetime 请求
搜索功能去抖动问题导致请求过多,debounceTime
无法正常工作。
<search"></search>
search(argument: string): void {
this.argument = argument;
this.searchService
.getSuggestions(this.argument )
.pipe(debounceTime(8000),distinctUntilChanged(),take(1))
.subscribe(
(suggestions) => {
this.suggestions= suggestions;
}
);
}
解决方法
您当前的实现不起作用的原因是您每次输入一个字符时都会创建一个新订阅。
search(argument: string): void {
// you don't need to do this
this.argument = argument;
// or this
this.live = this.argument.length >= 3;
if (this.live) {
this.searchService
.getSuggestions(this.argument )
.pipe(debounceTime(8000),distinctUntilChanged(),take(1))
// This subscription is then called every time you enter a value
.subscribe(
(suggestions: Array<string>) => {
this.suggestions= suggestions;
this.changeDetection.detectChanges();
}
);
}
我会像这样为您的搜索输入使用表单控件:
<input [formControl]='myControl'>`
在您的 TS 中,将其声明为类变量:
myControl = new FormControl();
FormControl
将 valueChanges
公开为您可以订阅的 observable。
那么你可能想做这样的事情:
suggestions$ = this.myControl.valueChanges.pipe(
// use an RxJS filter here instead of using class variables like you were earlier
filter(searchTerm => searchTerm?.length >= 3),debounceTime(8000),// switchMap will subscribe to the inner observable
// and cancel any in flight XHR requests if you create a new one
switchMap(valueChange =>
this.searchService.getSuggestions(valueChange)
)
)
我假设您将使用某种 *ngFor
来遍历返回的建议,如下所示:
<suggestion
*ngFor="let suggestion of suggestions$ | async"
[suggestion]="suggestion"
></suggestion>
使用 async
管道可确保您的订阅在组件销毁时得到整理。您可以通过其他方式做到这一点(您使用 take(1)
是在正确的道路上),但我的建议(双关语:D)是在可能的情况下使用 async
管道。
您好,请尝试使用以下代码来实现预输入功能
this.searchService
.getSuggestions((this.argument)).pipe(
debounceTime(8000),switchMap((this.argument) => {
// Any other operation
})
)
.subscribe((res) => {
// Result
});
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。