javascriptangulartypescriptrxjsangular-resource

Debouncing a search term when using the new Angular Resource API?


With RxJS we could debounce keystrokes like this prior to performing an http request.

this.query$.pipe(
    debounceTime(500),
    distinctUntilChanged(),

Does the new Angular Resource API have a way to debounce an input field prior to updating request parameters?


Solution

  • In the forseable future there is no plan to add debounce to the resource itself.

    This topic has been discussed in this GH Issue.

    The most straight forward solution to add some debounce to a resource would be to "wait" in the loader.

    export class AppComponent {
      inputText = signal('text');
    
      resource = resource({
        request: this.inputText,
        loader: async (param) => {
      
          // Debouncing: 300 ms
          await wait(300, param.abortSignal);
      
          return await Promise.resolve(Math.random())
        },
      });  
    
      ResourceStatus = ResourceStatus;
    }
    

    With the wait function that could be implemented this way:

    function wait(ms: number, signal: AbortSignal) {
      return new Promise<void>((resolve, reject) => {
        const timeout = setTimeout(() => resolve(), ms);
    
        signal.addEventListener('abort', () => {
          clearTimeout(timeout);
          reject(new Error('Operation aborted'));
        }, { once: true });
      });
    }
    

    This solution is kinda convinent because it keep the resource in the Loading status, which matches the expected behavior by users : When I type I want the app to "search".