#Angular Signals: Triggering an API Call Each Time a Signal Changes

5 messages · Page 1 of 1 (latest)

high bridge
#

Hello!

I'm currently learning about signals in Angular and experimenting with triggering API calls when a signal value changes.

Here's my setup:

  1. I have a numberId signal that increments each time a button is clicked.
  2. My goal is to trigger a new API call each time numberId changes to fetch data based on the updated value.

Here's the challenge:

I tried using computed to monitor numberId and placed toSignal inside the computed function to handle the API call, but I'm getting an NG0602 error. The Angular documentation mentions that toSignal shouldn't be used inside computed directly, but I'm not sure about the best practice to handle this pattern.

Could anyone help clarify the correct way to use toSignal to achieve this? Or is there an alternative approach I should take for reactive API calls based on signal changes? Any insights or examples would be much appreciated!

stackblitz example :- https://stackblitz.com/edit/stackblitz-starters-ixrehb?file=src%2Fmain.ts

Thank you!

An angular-cli project based on @angular/animations, @angular/common, @angular/compiler, @angular/core, @angular/forms, @angular/platform-browser, @angular/platform-browser-dynamic, @angular/router, core-js, rxjs, tslib and zone.js

limpid lichen
#

Personally I would do it this way:

readonly value = signal(0);
readonly value$ = toObservable(value);
readonly data = toSignal(
  this.value$.pipe(
    switchMap(value => this.dataService.load(value))
  )
);
ivory ferry
#

You're looking for resource() 🙂 coming soon in v19

limpid lichen
#

😮 Mind blown!

high bridge