royneedshelp
royneedshelp

Reputation: 173

How can RxMethods be reused in SignalStore

I am using ngrx/SignalStore to manage my state for a page containing a number of components. I provide the store on the route to this page.

By doing this I am able to use ngrx/router-store to retrieve the id of the item I'm displaying and initiate the load of the data from within the Store

  withHooks({
    onInit(store, store = inject(Store<State>)) {
      const id$ = store.select(selectRouteParam('id')).pipe(
        map((id) => (id ? parseInt(id) : null)),
        filter((id) => !!id),
        distinctUntilChanged(),
        takeUntilDestroyed()
      );
      store.load(id$);
    },
  })

My load method combines data from a number of sources but is basically:

      const load = rxMethod<number>(
        pipe(
          switchMap((id: number) => myAPIService.getById(id).pipe(tapResponse({next:....

I want to create other methods in the store to perform deletesById and updatesById. These will also be RxMethods and call APIs to do the updates. Following the API calls I want the state to refresh, essentially by calling load again (I don't have the new state locally to just update it without the API call - things like last updated timestamps) .

Would it be an antipattern to call an RxMethod from a tap operator in another rxMethod? It doesn't feel right but not sure how else I can re-use all my logic in load?

Upvotes: 1

Views: 106

Answers (1)

Ihor
Ihor

Reputation: 736

Currently, it seems like calling a RxMethod from a tap operator is the only "proper" way, since it's not an Observable to use in operators like switchMap.

The only problem is that your methods have to be in the correct declaration order, etc:

  withMethods(store => {
    _methodA: rxMethod(...)
  }),

  withMethods(store => {
    _methodB: rxMethod(
      pipe(
        tap(() => store._methodA())
      )
    )
  }),

Otherwise, you'll get an error: Property '_methodA' does not exist on type ...

Upvotes: 0

Related Questions