Change detection with RxJs Angular Signals, how to read new data in observable?

743 views Asked by At

I am attempting to utilise Angular's new Signal feature but struggling with reactivity.

Current Method

From understanding so far, to work with RxJS and Signals correctly the output of this observable needs to be converted to a signal using the toSignal() function, previously fromObs()

  response_signal = toSignal(this.response$ =
     this.apiService.getListApiV1O(
   ))

The signal can be read and displayed sucessfully read, likd this:

    <div *ngIf="response_signal()">
      <div *ngFor="let item of response_signal().items">
          <label>{{ item.name }}</label>
          <small>{{ item.website }}</small>
      </div>
    </div>

Issue

Here is the point at which I am lost. Typically Subjects/Event Emitters were considered the best solution to ensure reactivity. Signals supposedly have enhanced change detection features. I am however struggling with how they would be implmented here.

Does anyone know how to acheive reactivity if the observable has fresh data?

2

There are 2 answers

5
Kibé M.C On

You can try this by using computed

response_signal = computed(() => { this.apiService.getListApiV1O() })

0
Sharikov Vladislav On

It is what you need?

export class MyComponent {
  apiService = inject(ApiService);
  response$ = this.apiService.getListApiV1O();
  response_signal = toSignal(this.response$, { initialValue: {items: []} });
}
  1. You describe your observable.
  2. You describe your signal correctly with an initialValue
  3. You use your signal in a template than

You need an initial value or the code will fail, because you try to read items of undefined.

I also prepared a small example: https://stackblitz.com/edit/stackblitz-starters-vjpukj?file=src%2Fmain.ts

Tell me if you have any issues with that.