Angular 15 - How to Properly debounce input in Reactive Forms to Optimize Performance?
I've been struggling with this for a few days now and could really use some help... I'm facing performance issues in my Angular 15 application when handling user input via a reactive form. I have a search input field tied to an observable stream that triggers an API call on every key stroke. This leads to excessive requests being sent to the server, and sometimes I hit rate limits, causing temporary bans. I want to implement debouncing on the input to limit the number of API calls. I tried using the `debounceTime` operator from RxJS in my component, but I'm not seeing the expected results. Hereβs the code I have so far: ```typescript import { Component, OnInit } from '@angular/core'; import { FormBuilder, FormGroup } from '@angular/forms'; import { Subject } from 'rxjs'; import { debounceTime, switchMap } from 'rxjs/operators'; @Component({ selector: 'app-search', templateUrl: './search.component.html', styleUrls: ['./search.component.css'] }) export class SearchComponent implements OnInit { searchForm: FormGroup; private searchSubject = new Subject<string>(); constructor(private fb: FormBuilder) { this.searchForm = this.fb.group({ query: [''] }); } ngOnInit() { this.searchForm.get('query')?.valueChanges.pipe( debounceTime(300), switchMap(query => this.searchApi(query)) ).subscribe(results => { console.log(results); }); } searchApi(query: string) { // Replace with actual API call return of(`Searching for: ${query}`); } } ``` I expect the API to be called only after 300 milliseconds of inactivity in the input field. However, it seems like the API is still being hit multiple times as I type. I also tried moving the `debounceTime` before the `valueChanges` observable, but that didn't work either. Additionally, there's no error message, but the performance is definitely suffering and the console shows multiple logs of the search results before I even pause typing. Am I missing something in the implementation? Any best practices to apply here would be greatly appreciated. My development environment is Ubuntu. Am I missing something obvious? Any ideas what could be causing this?