I have started to slowly embrace the new Angular's Signal in my projects. I stumbled upon the following scenario, and while it works, I wonder if this is the "Angular way" of doing it.
In my component, I have a signal which lacks of an initial value, so I initialise it like this:
private readonly _id: Signal<string | undefined> = signal(undefined);
Only on ngOnInit
I'm really able to set the id (e.g. this._id.set('valid-id')
);
The thing is that I need the id in order to perform an Http request. In an Observable world, I'd go in this direction:
public readonly result$ = toObservable(this._id).pipe(
filter(Boolean),
switchMap((id) => this.myService.getById(id))
);
As a novice in the Signals world, I'd go like this:
public readonly result = toSignal(
toObservable(this._id).pipe(
filter(Boolean),
switchMap((id) => this.myService.getById(id))
),
{ initialValue: [] }
);
But I'm afraid that maybe I'm a little biased towards my love for RxJS and Observables :)
So I wonder if there's an Angular way to do this instead? Perhaps I have to use compute()
or effect()
? Calling .subscribe()
is definitely not an option!
result
will be read in the template, your last code example, not - the first example. Use signals in the template, but for any reactivity that requires functional of Observables, it is still better to implement it using Observables. – Oneiromancyresult
would be consumed in the template. What if I want to display a loading indicator, how could that be integrated? I feel like my head is still full of RxJS operators and I'm tempted to usetap()
to toggle anisLoading
signal :) – Drue