Angular Signals: How to handle requests to API

Discussão em 'Angular' iniciado por Martin Hochmair, Fevereiro 24, 2025.

  1. 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!

    Continue reading...

Compartilhe esta Página