我在应用程序中使用信号存储来管理与项目和站点相关的状态。这是我当前的实现:
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
更改加载项目的最佳实践是什么?
基本上这是我的解决方案。我不太确定更新存储值是否可能会产生问题......
withHooks({
onInit({ loadSites, selectedSite, loadProjectsBySiteId }) {
loadSites();
effect(() => {
const selectedSiteId = selectedSite()?.id;
if(selectedSiteId) {
loadProjectsBySiteId(selectedSiteId);
}
}, { allowSignalWrites: true });
}