在使用的 Angular 项目中,NX Workspace
我有一个空的根存储和不同的功能状态。
我最初初始化了一些不属于实体模型的特征状态属性(参见LandleistungState
下面的状态接口)。然后在稍后阶段将实体添加到状态中。
这会在选择器中产生一些问题,因为我不能使用selectAll
或selectEntities
方法,因为我得到一个异常,说实体是未定义的。这很清楚,因为还没有实体存在,但这让我怀疑我的方法是否仍然正确,或者我可能犯了一些概念上的错误。
有没有办法在像我这样的情况下继续使用selectAll
或selectEntities
方法,状态已经初始化,但还没有存储实体?在这种情况下,方法不应该简单地返回 null 吗?
根存储 - app.module.ts
StoreModule.forRoot({}, {
metaReducers: !environment.production ? [] : [],
runtimeChecks: {
strictActionImmutability: true,
strictStateImmutability: true,
}
}),
EffectsModule.forRoot([]),
特征状态
imports: [
StoreModule.forFeature(
'landleistungen',
fromLandleistungen.reducer
),
EffectsModule.forFeature([LandleistungenEffects]),
],
特征减速器
export interface LandleistungState extends EntityState<LandleistungenEntity> {
// These properties are initialized before any entity is added to the state
tabsConfigLoaded: boolean;
currentTabIndex: number;
}
export const landleistungenAdapter: EntityAdapter<LandleistungenEntity> =
createEntityAdapter<LandleistungenEntity>({
selectId: (tabs) => tabs.tabIndex,
});
export const initialState: LandleistungState =
landleistungenAdapter.getInitialState({
tabsConfigLoaded: false,
currentTabIndex: 0,
});
...
实体模型
export interface LandleistungenEntity {
tabIndex: number;
formValue: any;
}
特征选择器
export const getLandleistungenState = createFeatureSelector<LandleistungState>(
'landleistungen'
);
const { selectAll, selectEntities } = landleistungenAdapter.getSelectors(
getLandleistungenState
);
export const getActiveTabIndex = createSelector(
getLandleistungenState,
(state: LandleistungState) => state.currentTabIndex
);
export const getAllLandleistungen = createSelector(
getLandleistungenState,
(state: LandleistungState) => selectAll(state) // <-- THIS TRIGGERS THE ERROR
);
export const getTabFormData = createSelector(
getLandleistungenState,
getActiveTabIndex,
(state, activeIndex) => {
// THIS WAY IT WORKS, BUT IT LOOKS MORE LIKE A WORKAROUND
return state.entities ? state.entities[activeIndex]?.formValue : null;
}
);