I use RxJS filter pipe to trigger data reload from the REST server only when selectedId is not null. How do I transfer the observable into signal/computed signal achieving same effect as with the filter pipe?
this.selectService.selectedId$.pipe(filter(selectedId=> selectedId!= null)).subscribe(
this.restService.loadData(...);
);
Ideally I would like the signal not to trigger when then value is null/undefined, cause then it would cause a data load for null id from the server.
Is this even possible to do with computed signals?
I use RxJS filter pipe to trigger data reload from the REST server only when selectedId is not null. How do I transfer the observable into signal/computed signal achieving same effect as with the filter pipe?
this.selectService.selectedId$.pipe(filter(selectedId=> selectedId!= null)).subscribe(
this.restService.loadData(...);
);
Ideally I would like the signal not to trigger when then value is null/undefined, cause then it would cause a data load for null id from the server.
Is this even possible to do with computed signals?
Share Improve this question edited Mar 20 at 10:28 jonrsharpe 122k30 gold badges268 silver badges476 bronze badges asked Mar 20 at 10:04 DakadoDakado 1635 silver badges18 bronze badges1 Answer
Reset to default 0You can try rxResource
to trigger the API
- When the
request
callback returns a valid value - If the request returns
undefined
then the API call is not made (Since the parameters required for therxResource
are not ready).
Using rxResource
:
selectedId = toSignal(this.selectService.selectedId$);
apiData = rxResource({
request: () => {
const selectedIdValue = this.selectedId();
if(selectedIdValue) {
return selectedIdValue;
} else {
return undefined; // loader method will not run.
}
},
loader: ({ request: selectedId }) => this.restService.loadData(selectedId),
});
Using computed
and rxResource
:
I think you can also use a computed
signal to achieve this, we can move the logic to the computed
signal and return either a value or undefined
.
selectedId = toSignal(this.selectService.selectedId$);
apiDataRequest = computed(() => selectedIdValue || undefined);
apiData = rxResource({
request: () => this.apiDataRequest(),
loader: ({ request: selectedId }) => this.restService.loadData(selectedId),
});
- signals decision chart
- When Should We (NOT) Use a Signal effect()?