如何通过ID ngrx获取实体

时间:2019-05-28 07:16:55

标签: redux ngrx

我有以下商店

export const featureAdapter: EntityAdapter<IProduct> = createEntityAdapter<IProduct>({
  selectId: model => model.id,
});

export interface State extends EntityState<IProduct> {
  selectedProduct?: IProduct;
  isLoading?: boolean;
  error?: any;
}

export const initialState: State = featureAdapter.getInitialState({
  selectedProduct: IProduct,
  isLoading: false,
  error: null
});

我希望我选择的产品始终指向一个实体并获取其更新。我相信,由于操作总是在创建新对象,因此无法建立链接,因此我决定将selectedProduct从引用更改为简单ID。

export const initialState: State = featureAdapter.getInitialState({
  selectedProduct: string,
  isLoading: false,
  error: null
});

但是,如何更改具有相同ID的实体,并在观察到的实体上进行更新(如果更改了)?

我尝试了

export const getSelectedProduct: MemoizedSelector<object, any> = createSelector(
  selectAllEntities,
  selectedProduct,
  (entities, id) => entities[id]
);


export const selectEntityById = createSelector(
  selectAllEntities,
  (entities, props) => entities[props.id]
);

我的问题是 这是通过id选择实体的唯一方法吗?

this.store$.pipe(
  select(ProductStoreSelectors.selectEntityById, { id: product.id }),
  map(product => console.log(product))
)

和       this.store $ .select(ProductStoreSelectors.getSelectedProduct).subscribe((product:string)=> {         console.log(产品)       })

当我更改所选产品ID时永远不会触发

编辑:

selector上的reduce执行以下操作

const SET_SELECTED_PRODUCT = (state: State, action: featureAction.SetSelectedProduct) => {
  return {
    ...state,
    selectedProduct: action.payload.product.id
  };
};

1 个答案:

答案 0 :(得分:0)

在选择器中尝试以下操作:

export const selectEntityById = (id: number) => createSelector(
  selectAllEntities,
  (entities) => entities[id]
);

和您选择的内容

select(ProductStoreSelectors.selectEntityById(id))