angularngrxngrx-signal-store

Angular - Ngrx signal store


I'm trying out Ngrx signal store. I watched couple of tutorials and read official documentation. Videos on youtube are pretty simple and docs didn't cover that. I'm trying to use withHooks onInit method to fetch data on store init, but problem is that API endpoint I'm using requires param, but passing params into method is not covered, or at least I didn't manage to find solution. Should I ditch fetching in signalStore onInit and move to standard component ngOnInit? Also that prop is passed into component over signal input. Example code below.

export const PostsStore = signalStore(
  withState<PostsStateInterface>({
    post: {},
    error: null,
    isLoading: false
  }),
  withMethods((store, postsService = inject(PostsService)) => ({
    loadPosts: rxMethod<number>(
      pipe(
        switchMap((id) => {
          return postsService.getPost(id).pipe(
            tap((posts) => {
              patchState(store, { post })
            })
          )
        })
      )
    )
  })),
  withHooks({
    onInit(store) {
      store.loadPost(id) // Call the loadPost method with the id, how to get the id?
    },
  })
)

@Component({
  ...
  standalone: true,
  providers: [PostsStore],
  imports: [
    ...
  ],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class ImageProcessing360ContainerComponent {
  id = input.required<number>()
  store = inject(PostsStore)
}

Solution

  • What you are looking for is covered under

    1. https://ngrx.io/guide/signals/signal-store#reactive-store-methods
    2. https://ngrx.io/guide/signals/signal-store#putting-it-all-together

    So what you need to do according to the docs is not to load the data in the stors withHooks-> onInit -> loadPosts but rather in the component in the ngOnInit -> store.loadPosts(id).