每当信号存储中的信号属性发生变化时,加载数据取决于信号属性

问题描述 投票:0回答:1

我在应用程序中使用信号存储来管理与项目和站点相关的状态。这是我当前的实现:

interface State {
  selectedProject: Project | null,
  selectedSite: Site | null,

  projects: Project[],
  sites: Site[],
}

export const Store = signalStore(
  withState<State>({
    selectedProject: null,
    selectedSite: null,

    projects: [],
    sites: []
  }),

  withMethods(state => {
    const sitesService = inject(SitesService);
    const projectsService = inject(ProjectsService);

    return {
      loadSites: async () => {
        const sites = await sitesService.getSites();
        patchState(state, { sites });
      },
      loadProjectsBySiteId: async (siteId: number) => {
        const projects = await projectsService.getProjectsBySiteId(siteId);
        patchState(state, { projects });
      },
      setSelectedSite: (selectedSite: Site) => {
        patchState(state, { selectedSite, selectedProject: null });
      },
      setSelectedProject: (selectedProject: Project) => {
        patchState(state, { selectedProject });
      }
    };
  }),

  withHooks({
    onInit({ loadSites }) {
      loadSites();
    }
  })
);

每当

selectedSite
发生变化时,我都需要加载项目。目前,我不确定在信号存储设置中实现此目的的最佳方法。

我要么考虑以某种方式使用 withCompulated,要么在 setter setSelectedSite 内部执行此操作(在此处触发 fetch 或...)

在此上下文中基于

selectedSite
更改加载项目的最佳实践是什么?

angular typescript signals ngrx state-management
1个回答
0
投票

基本上这是我的解决方案。我不太确定更新存储值是否可能会产生问题......

withHooks({
onInit({ loadSites, selectedSite, loadProjectsBySiteId }) {
  loadSites();
  effect(() => {
    const selectedSiteId = selectedSite()?.id;
    if(selectedSiteId) {
      loadProjectsBySiteId(selectedSiteId);
    }
  }, { allowSignalWrites: true });
}
© www.soinside.com 2019 - 2024. All rights reserved.