我花了 2 天的时间来编写 featureA(“场景”)模块和嵌套的 featureB(“意图”)模块的状态。
这是我想要的状态结构(结构 1):
{
authentication: { ... },
router: { ... },
scenarios: {
resources: { ids: { ... }, entities: { ... } },
intents: {
resources: { ids: { ... }, entities: { ... } }
}
}
}
我也很高兴(结构 2):
{
authentication: { ... },
router: { ... },
scenarios: { ids: { ... }, entities: { ... } },
intents: { ids: { ... }, entities: { ... } },
}
尽管它没有反射(reflect)我的模块的结构。
结构 1 的问题是 scenarios/reducers/index.ts
公开了 ActionReducerMap
,scenarios/modules/intents/reducers/index.ts
还公开了一个 ActionReducerMap ,我不知道如何组合它们。由于类型冲突,我尝试的所有内容甚至都无法编译。
结构 2 的问题在于,由于 IntentsModule
在首页加载时未加载以及其他原因,状态的 intents
部分不断从状态中删除。应用程序的 reducer 正在完成其工作。
这是代码:
/scenarios/scenarios.module.ts:
import { reducers, getInitialState } from './reducers';
@NgModule({
imports: [
...,
ScenariosRoutingModule,
StoreModule.forFeature('scenarios', reducers, { initialState: getInitialState }),
EffectsModule.forFeature([ScenariosEffects]),
],
})
export class ScenariosModule {}
/scenarios/reducers/index.ts:
import * as fromRoot from '../../../app.reducers';
import * as fromScenarios from './scenarios.reducers';
import * as fromIntents from '../modules/intents/reducers';
export interface ScenariosState {
resources: fromScenarios.State;
intents: fromIntents.IntentsState;
}
export interface State extends fromRoot.State {
scenarios: ScenariosState;
}
export const reducers: ActionReducerMap<ScenariosState> = {
resources: fromScenarios.reducer,
intents: fromIntents.reducers, <-- This is the part with types conflicts
};
/scenarios/modules/intents/intents.module:
import { reducers, getInitialState } from './reducers';
@NgModule({
imports: [
...,
IntentsRoutingModule,
StoreModule.forFeature('intents', reducers, { initialState: getInitialState }), <-- Also this part seems to add 'intents' as a top-level property of state
EffectsModule.forFeature([IntentsEffects]),
],
})
export class IntentsModule {}
/scenarios/modules/intents/reducers/index.ts:
import * as fromIntents from './intents.reducers';
export interface IntentsState {
resources: fromIntents.State;
}
export interface State {
intents: IntentsState;
}
export const reducers: ActionReducerMap<IntentsState> = {
resources: fromIntents.reducer,
};
export function getInitialState(): IntentsState {
return {
resources: fromIntents.initialState,
};
}
最佳答案
导入
和导出
根AppModule
中的结构2
IntentsModule
。导入
根AppModule
中IntentsModule
后面的ScenariosModule
。
不要在ScenariosModules
下嵌套各种IntentsModules
。相反,尽可能创建分离并扁平化您的项目结构,这是结构 2
所固有的要求。
我发现,对于大多数情况(与身份验证相关的功能除外),一个好的方法是为每个功能创建两个模块,以便延迟加载在一起,同时将状态管理与用户界面解耦,但这些相应的模块应该共享一个相同形状的 API
即:
- (
FrameworkLayoutModule
和FrameworkStoreModule
) 和 (AuthModule
)。
随后,可根据需要由 SecureModule
或 PublicModule
延迟加载可重用功能。
关于angular - 如何使用 @ngrx/store 和 @ngrx/entity 嵌套延迟加载功能模块的状态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51764229/