最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

rxjs - Convert filter pipe to Angular computed signal - Stack Overflow

programmeradmin6浏览0评论

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 badges
Add a comment  | 

1 Answer 1

Reset to default 0

You 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 the rxResource 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()?
发布评论

评论列表(0)

  1. 暂无评论