I’m migrating an angular aplication to use signals and input signals, but found a situation I’m not satisfied.
With previous @Input()
I could define a setter to trigger an “effect” when a specific input changed, and I would setup an observable for a request to the server, something like
@Input()
set id(value: number) {
this.loading = true;
this.entity$ = this.service.findById(value).pipe(finalize(() => {
this.loading = false;
}));
}
I like to avoid using ngOnChanges
as I can avoid validating which input changed.
With signals the closest I could find is to use an effect
to trigger the query, but the documentation doesn’t really recommend it
Effects are rarely needed in most application code, but may be useful in specific circumstances
Avoid using effects for propagation of state changes. This can result in ExpressionChangedAfterItHasBeenChecked errors, infinite circular updates, or unnecessary change detection cycles.
Because of these risks, setting signals is disallowed by default in effects, but can be enabled if absolutely necessary.
As I have to set the loading
signal to true, I would be breaking the last part
effect(() => {
this.loading.set(true);
this.entity$ = this.service.findById(value).pipe(finalize(() => {
this.loading.set(false);
}));
})
I have also found a way using toObservable()
on the input signal, but it uses effetc()
under the hood so I suppose I’m limited in the same way.
Is there a recommended approach? Am I dependent of ngOnChanges
for this scenarios?