I'm making a search field. Before making the API call I want to wait for 2 seconds after the user has finished typing. Here is my code:
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);
});
}
My code is not waiting for 2 secs. The console log is happening immediately. Please correct my mistake.
CodePudding user response:
I think using a subject will be a better way to achieve what you want
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);
}