Reputation: 11
I am trying to utilse some of Angular's new reactivity with Signal. I am following this workflow, and converting one of my observables into a signal, this is then being read and displayed on my screen.
https://angular.dev/guide/signals/rxjs-interop#tosignal
Working Example
** T.S **
response_obs$ =
this.apiService.getResponse();
response_signal: Signal<any> = toSignal(response_obs$, {initialValue: 0})
** HTML **
<div *ngIf="response_signal()">
<div class="item" *ngFor="let item of response_signal().items ">
<label>{{ item.name }}</label>
<small>{{ item.website }}</small>
</div>
</div>
This all works and prints correctly. We have replaced the async pipe by using the toSignal() function.
What I am trying to achevive next is reacitvity. When I post to this API in aother part of the application the observable will have new data to emit, if I refresh the webpage this appears but the change is not registered.
The update to the observable can be triggered via and Event Emitter, is there tooling within Angular Signals workflow that can be used here?
Upvotes: 0
Views: 1879
Reputation: 20599
Create an Observable to call getResponse()
every time a response changes. Initiating it with a BehaviorSubject makes the most sense so that it will immediately start an observable stream. The create a stream inside of toSignal()
(you don't even have to assign it to a variable) that chains emissions to calls to the service.
TS
responseChanged = new BehaviorSubject<void>(undefined);
response_signal = toSignal(
this.responseChanged.pipe(
switchMap(() => this.apiService.getResponse())
),
{ initialValue: 0 }
);
HTML
<app-something (onChange)="responseChanged.next()" />
Upvotes: 1