如何在ngrx中调用选择器内部的选择器?
我有来自适配器的选择器:
const { selectAll, selectEntities } = productAdapter.getSelectors();
还有另一个选择器来获取产品,然后通过id将产品传递到道具中。
const getProductsEntities = createSlector(getProductState, (state) => selectEntites(state));
const selectProductById = createSelector(getProductsEntities , (entities, props) => {
return entities[props?.productId]
});
现在我想做另一个选择器,并使用selectProductById
选择器。
const selectProductViewById = createSelector(
selectProductById,
(product) => {
...
}
)
productView$ = this.store.pipe(select(selectProductViewById, { id: 1 });
但这是行不通的。我还得到了一个错误,参数传递是错误的。
那么,如何在带有参数的选择器内部调用选择器?
首先,您不必通过调用createSelector
来创建新的getProductsEntities
选择器。您可以在对store
的select
调用中直接使用selectEntities
。或者,如果你喜欢另一个名字,你可以简单地使用:
const getProductsEntities = selectEntities;
但是,为了回答您的问题,以下是如何使用工厂选择器实现一个以参数为输入的选择器:
const selectProductById = (productId: string) => createSelector(
getProductsEntities,
(entities) => entities[productId]
);
const selectProductViewById = (productId: string) => createSelector(
selectProductById(productId),
(product) => {
...
}
)
productView$ = this.store.select(selectProductViewById(1));
在选择器中使用props?.productId
,但在调用选择器时使用{ id: 1 }
。
这应该是相同的属性键。