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

angular - How to trigger a method in one NgRx Signal Store when a property in another store updates? - Stack Overflow

programmeradmin2浏览0评论

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());
      }
    };
  })
);

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论