如何在角度延迟加载模块中访问ngrx实体选择器?

时间:2020-04-30 18:27:25

标签: angular typescript ngrx ngrx-entity

我正在尝试使用NGRX状态管理库实现应用程序。我能够创建动作和化简器以将数据推入延迟加载状态。但是我正在努力实现选择器以将数据获取到组件。这是我到目前为止所做的

reducer / job-file.reducer.ts ,这里我正在使用ngrx实体插件

import {Action, createReducer, on} from '@ngrx/store';

import * as JobFileActions from '../actions';
import {JobFile} from '../../models/job-file.model';
import {createEntityAdapter, EntityAdapter, EntityState} from '@ngrx/entity';

export const jobFIleFeatureKey = 'jobFile';

export const adapter: EntityAdapter<JobFile> = createEntityAdapter<JobFile>({
  selectId: (jobFile: JobFile) => jobFile.jobRefId
});

export interface State extends EntityState<JobFile> {
  selectedJobRefId: string;
}

export const initialState: State = adapter.getInitialState({
  selectedJobRefId: null,
});

export const reducer = createReducer(
  initialState,
  on(JobFileActions.AddJobFile as any, (state: State, action: {jobFile: JobFile}) => {
    return adapter.addOne(action.jobFile, state);
  })
);

export const selectedJobRefId = (state: State) => state.selectedJobRefId;

reducer / index.ts

import {ActionReducerMap } from '@ngrx/store';
import * as fromJobFile from './job-file.reducer';

export const scheduleFeatureKey = 'schedule';

export interface ScheduleState {
  [fromJobFile.jobFIleFeatureKey]: fromJobFile.State;
}

export const reducers: ActionReducerMap<ScheduleState> = {
  [fromJobFile.jobFIleFeatureKey]: fromJobFile.reducer
};

schedule.module.ts

import * as fromSchedule from './store/reducers';
@NgModule({
  declarations: [ScheduleComponent, ContainerDetailsComponent, AssignScheduleComponent, LegComponent, ResourceOverviewPanelComponent,
    ResourceNavigationComponent],
  imports: [
    SharedModule,
    ScheduleRoutingModule,
    StoreModule.forFeature('schedule', fromSchedule.reducers)
  ]
})

selectors.ts ,这是我现在正在努力的地方

import { adapter as jobFileAdaptor } from '../reducers/job-file.reducer';
import {createFeatureSelector, createSelector} from '@ngrx/store';
import { ScheduleState } from '../reducers';

export const selectJobFileState = createFeatureSelector<ScheduleState>('jobList');

export const a = createSelector(selectJobFileState, jobFileAdaptor.getSelectors().selectAll);
export const {
  selectIds: selectAllJobIds,
  selectAll: selectAllJobFiles,
  selectEntities: selectAllJobEntities,
  selectTotal: selectTotalJobs
}  = jobFileAdaptor.getSelectors();

我遇到了错误。有谁知道如何编写这些选择器 enter image description here

1 个答案:

答案 0 :(得分:1)

问题似乎是selectJobFileState的类型,因为ScheduleState不是EntityState的实现。相反,它包含一个以EnitityState作为其值的键。

// In your reducers index.ts
export { State as JobFileEntityState } from './job-file.reducer';

// In selectors.ts
import { JobFileEntityState } from '../reducers';

export const selectJobFileState = createFeatureSelector<JobFileEntityState>('jobList');

旁注:如果要在selectors.ts中将功能选择器键指定为字符串文字,那么为什么还要在其他地方使用变量。始终如一。您可能应该导入jobList功能键变量,并使用它代替字符串。