我正在创建一个搜索字段。在进行API调用之前,我想在用户完成输入后等待2秒。下面是我的代码:
HTML:
<input type="text" pInputText (input)="onInput()" [(ngModel)]="value1" placeholder="Search">
TS:
searchTerm : Subscription;
onInput() {
this.searchTerm = from(this.value1);
this.searchTerm
.pipe(
map((event: any) => this.value1),
debounceTime(2000),
distinctUntilChanged()
)
.subscribe((res: any) => {
console.log(res);
});
}
我的代码没有等待2秒。控制台日志正在立即发生。请纠正我的错误。
我认为使用主题将是一个更好的方法来实现你想要的
searchTerm: Subject<any> = new Subject();
ngOnInit(){
this.searchTerm
.pipe(
map((event: any) => this.value1),
debounceTime(2000),
distinctUntilChanged()
)
.subscribe((res: any) => {
console.log(res);
});
}
onInput() {
this.searchTerm.next(this.value1);
}