如何在NgRx Entity Adapter中使用复合主键?
在NgRx中使用复合主键的解决方案
NgRx的EntityAdapter要求selectId必须返回string或number类型,不能直接返回数组形式的复合主键,但我们可以通过把复合键拼接成唯一字符串的方式来实现需求。
解决方法:将复合主键拼接为单一字符串
修改你的selectId函数,把year、month、dayofmonth拼接成一个唯一的字符串(比如用连字符分隔),就能满足类型要求:
// 我的DailyEvent实体由[year, month, dayofmonth]唯一标识 export interface DailyEvent { year: string, month: string, dayofmonth: string, eventDesc: string } ... export const adapter: EntityAdapter<DailyEvent> = createEntityAdapter<DailyEvent>({ selectId: (evt) => `${evt.year}-${evt.month}-${evt.dayofmonth}` // 复合键拼接为唯一字符串 })
后续使用注意事项
当你需要通过主键查找实体时,也要遵循相同的拼接规则生成目标ID:
// 示例:获取2024年5月10日的事件 const targetId = `2024-05-10`; const targetEvent = adapter.getOne(targetId, state.dailyEvents);
这种方式既保留了复合主键的唯一性,又完全符合NgRx EntityAdapter的要求,不会再出现类型错误。
内容的提问来源于stack exchange,提问作者gau000
相关产品推荐
相关产品推荐

