NGRX-结合选择器和道具

时间:2019-02-15 10:19:23

标签: ngrx ngrx-store

当其中之一需要道具时,如何组合减速器?

我有以下模型:

interface Device {
  id: string;
  data: IDeviceData;
}

和DeviceReducer如下所示:

import { EntityState, EntityAdapter, createEntityAdapter } from '@ngrx/entity';
import { Device } from '../model/device';
import { SubnetBrowserApiActions } from 'src/app/explorer/actions';

export interface State extends EntityState<Device> { }

export const adapter: EntityAdapter<Device> = createEntityAdapter<Device>();

export const initialState: State = adapter.getInitialState();

export function reducer(
  state = initialState,
  action:
    | SubnetBrowserApiActions.SubnetBrowserApiActionsUnion
): State {
  switch (action.type) {
    case SubnetBrowserApiActions.SubnetBrowserApiActionTypes.LoadEntriesSucces: {
      return adapter.upsertMany(action.payload.entries, state);
    }

    default: {
      return state;
    }
  }
}

const {
  selectAll,
} = adapter.getSelectors();

export const getAllDevices = selectAll;

在另一个reducer中,当我想使用ID数组选择设备时,我使用以下代码:

export const getVisibleDrives = createSelector(
  [fromRoot.getAllDevices, getVisibleDrivesSerialNumbers],
  (devices, visibleDevicesIds) =>
    devices.filter((device) => onlineDevicesIds.includes(device.serialNumber)),
);

这段代码是非常重复的,因此我想添加add参数化选择器,该选择器将仅返回这些驱动器,这些驱动器在id中作为prop传递。我尝试做的事情如下所示:

DeviceReduced中的其他选择器

export const getDrivesWithIds = (ids: string[]) => createSelector(
  getAllDevices,
  devices => devices.filter(device => ids.includes(device.id))
);

然后以以下方式将它们组合:

export const getVisibleDrives = createSelector(
  getVisibleDrivesSerialNumbers,
  (ids) => fromRoot.getDrivesWithIds
);

这里的问题是此选择器的返回类型是

(ids: string[]) => MemoizedSelector<State, Device[]>

这使我无法使用此选择器做任何有用的事情。例如,我想按关键字过滤此列表,但无法在其上使用filter方法:

用法示例

export const getFilteredVisibleDrives = createSelector(
  [getVisibleDrives, getKeywordFilterValue],
  (visibleDrives, keywordFilter) => {
    return visibleDrives
      .filter(drive => // in this line there is an error: Property 'filter' does not exist on type '(ids: string[]) => MemoizedSelector<State, Device[]>'
        drive.ipAddress.toLowerCase().includes(keywordFilter.toLowerCase()) ||
        drive.type.toLowerCase().includes(keywordFilter.toLowerCase()) ||
        drive.userText.toLowerCase().includes(keywordFilter.toLowerCase())
      );
  },
);

1 个答案:

答案 0 :(得分:2)

选择器:

export const getCount = () =>   
  createSelector(     
    (state, props) => state.counter[props.id],     
    (counter, props) => counter * props.multiply
  );

组件:

this.counter2 = this.store.pipe(
  select(fromRoot.getCount(), { id: 'counter2', multiply: 2 })
);   
this.counter4 = this.store.pipe(
  select(fromRoot.getCount(), { id: 'counter4', multiply: 4 })
);

有关更多信息,请参见我的帖子NgRx: Parameterized selectors