Combine multiple signal inputs that trigger http call

A component accepts multiple inputs as signals, a change to any will trigger the call to http.

Published: 8/9/2024
import { catchError, combineLatest, filter, of, switchMap } from 'rxjs';

// props
plantIdInput = input<number>(0, { alias: 'plantId' });
pageInput = input<number>(1, { alias: 'page' });
limitInput = input<number>(1, { alias: 'limit' });
searchInput = input('', { alias: 'search' });

// data access
list = toSignal(
  combineLatest([
    toObservable(this.plantIdInput),
    toObservable(this.pageInput),
    toObservable(this.limitInput),
    toObservable(this.searchInput),
  ]).pipe(
    filter(([page, limit]) => page > 0 && limit > 0),
    switchMap(([plantId, page, limit, search]) =>
      this.variantsService.list$(plantId, page, limit, search).pipe(
        catchError((error) => {
          console.error('Error fetching variants:', error);
          return of(null); // Or handle error as needed
        })
      )
    )
  )
);