我正在使用NGRX存储一个简单的对象,但是当将该对象添加到状态树时,还添加了reducer的名称,当我强烈键入选择器并对其进行订阅时,这会产生问题
代码如下:
减速器:
export interface State extends AppState.State {
player: PlayerState;
}
export interface PlayerState {
currentSkick: ISkick;
}
export const initialState: PlayerState = {
currentSkick: null,
};
export const reducer = createReducer<PlayerState>(
initialState,
on(
PlayerActions.setCurrentSkick,
(state, action): PlayerState => {
return {
...state,
currentSkick: action.skick,
};
}
)
);
选择器:
const getCurrentSkickFeaturesState = createFeatureSelector<PlayerState >(
'player'
);
export const getCurrentSkick = createSelector(
getCurrentSkickFeaturesState,
(state) => state.currentSkick
);
动作:
export const setCurrentSkick = createAction(
'[Player] Set Current Skick',
props<{ skick: ISkick }>()
);
功能模块:
@NgModule({
imports: [
StoreModule.forFeature('player', { reducer }),
],
})
export class SkickPlayerModule {}
应用模块:
@NgModule({
declarations: [AppComponent ],
imports: [
BrowserAnimationsModule,
StoreModule.forRoot({}, {}),
StoreDevtoolsModule.instrument({
name: 'player',
maxAge:25,
logOnly: environment.production
})],
})
export class AppModule {}
Skick界面:
export interface ISkick {
fileVersion: string;
formatVersion: string;
title: string;
author: string;
authorEmail: string;
creationDate: Date;
uniqueId: string;
thumbnailLink: string;
frames: Frame[];
assets: Assets;
}
和组件:
//Dispatch the action set the current object
async loadSkick(zip: JSZip) {
let skickPlayer = await this.getFileToText(zip);
this.store.dispatch(PlayerActions.setCurrentSkick({ skick: skickPlayer }));
}
ngOnInit(): void {
//Subscribe the get the current object
this.store.select(getCurrentSkick).subscribe((skick) => {
this.skickPlayer = skick;
if (this.skickPlayer) this.performFrame(0);
});
}
由于ngrx正将减速器的名称添加到树中,如下图所示:
当尝试从订阅中读取对象时,该对象失败,因为该“还原器”名称已固定在树中。知道为什么吗?树中对象的结构应为Player.currentSkick,而不是player.reducer.currentSkick
答案 0 :(得分:1)
在模块中,如果您导入reducer像
import * as fromMyFeature from 'somewhere.reducer';
您应该像这样使用导入部分:
@NgModule({
imports: [
StoreModule.forFeature('player', fromMyFeature.reducerExportName),
],
})
export class SkickPlayerModule {}