Search code examples
ngrx-store

NgRX Store and rxMethod with specific condition


I'm using the NgRx Store and want to use the rxMethods at the ngOninit.

I follow the guideline of the NgRX Store for rxMethods. The sample is quite close what I'm looking for. But I have no clue how to adapt the given code.

I would like to have

fetchAllAgain=signal<boolean>(false);

ngOnInit():void{
  loadAllBooksByChange(fetchAllAgain);
}

The value should be changed on the UI - for the sake of simplicity I leave it with a simple init.

And I would like to run the method loadAllBooks as soon as fetchAllAgain will change to true.

loadAllBooksByChange=rxMethod<void>
  pipe(filter(fetchAllAgain),
    exhausMap(() => {
        .....

I'm not sure about

  1. if the signal fetchAllAgain should be queried in the rxMethod or outside. If outside then I only have the idea to implement with effect
  2. I'm not clear how to query the filter and than set the response.

Solution

  • No need to use effect, rxMethod will react to the source signal,you just may be need to make small modification to your code. here is an example of how to use filter and set response. Whenever fetchAllAgain changes from the ui rxMethod reacts to it.

    const loadAll = rxMethod<boolean>(
      pipe(
        filter((fetchAllAgain) => fetchAllAgain), 
        tap(() => patchState(store, { isLoading: true })),
        switchMap((load) => {
          return service.loadAll().pipe(
            tapResponse({
              next: (planets) => {
                console.log('Planets', planets);
                patchState(store, { planets, isLoading: false });
              },
              error: (err) => {
                patchState(store, { isLoading: false });
                console.error(err);
              },
            })
          );
        })
      )
    );