admin管理员组

文章数量:1356845

I am working with NgRx Signal Store in an Angular project, and I need to make one store DashboardStore reactively call a method when a property in another store FilterSelectionStore updates.

Use Case: FilterSelectionStore maintains a selectedFilters property, which i am updating whenever there is a change in filter selection

DashboardStore has a method loadDrivers, which should be executed whenever selectedFilters in FilterSelectionStore updates.

When selectedFilters updates in FilterSelectionStore, loadDrivers is not re-executed.How can I make DashboardStore reactively respond when selectedFilters in FilterSelectionStore updates?

Current Implementation: I have DashboardStore defined like this:

type TDashboardState = {
  drivers: TDriver[];
};

const initialState: TDashboardState = {
  drivers: []
};

export const DashboardStore = signalStore(
  // Initializes the store state
  withState(initialState),

  // Defines methods for loading drivers based on filters
  withMethods((store) => {
    const _driverService = inject(DriverService);

    return {
      loadDrivers: rxMethod<TSelectedFilters>(
        pipe(
          filter(({ anization, state, zones }) => !!anization && !!state && !!zones?.length),
          distinctUntilChanged(isEqual),
          switchMap(({ zones }) =>
            _driverService.fetchDrivers({ zones: zones! }).pipe(
              tapResponse<TDriver[], TResponse>({
                next: (operationResult) => {
                  patchState(store, { drivers: operationResult });
                },
                error: () => {
                  patchState(store, { drivers: [] });
                }
              })
            )
          )
        )
      )
    };
  }),

  // Hooks to watch for changes in another store
  withHooks((store) => {
    const _filterStore = inject(FilterSelectionStore);

    return {
      onInit() {
        // Load drivers on store initialization
        store.loadDrivers(_filterStore.selectedFilters());
      }
    };
  })
);

本文标签: