So I am new to signals and I am trying to use them more and more in our application. The part where I still cannot wrap my head around is the connection between rxJS and Signals. Because we are using angulars HTTP client, we have to deal with observables (which is not a bad thing). But now I am trying to make my code more reactive by updating a signals value by doing an API call whenever the ID of the scoped object(which is a signal itself) changes. This is what I came up with:
effect(() => {
this.apiService.hasSomething({
customerId: mySignalWhoseValueChanges()
}).subscribe(value => this.mySignal.set(value));
});
If i use mySignal() in my template and change mySignalWhoseValueChanges(), it will call the effect() because effect() listens for any signal changes that are used within it.
The thing is, I am 100% sure there is a better approach without using effect(), but I just do not know. I tried using toSignal() but this does not work as its not actually a signal thats referenced, but only the value at the time of creating it, or am I missing something:
this.mySignal = toSignal(this.apiService.hasSomething({
customerId: mySignalWhoseValueChanges()
}))
Thanks in advance!
You can combine a signal with an http request pretty easily.
You can use the
toObservablefunction to watch for changes in/on the signal, then trigger your http request when the id changes.Note: Signals are NOT meant to be a replacement for RxJS (at least not anytime soon). They are meant to work in unison.
To this this, you would take the following steps:
usersignal to watch for the current user. (this can be anything I chose a number).responsesignal to watch for the http response.usersignal.toObservableand pass yourusersignal as the parameter.responsesignal with the data.StackBlitz Example