【发布时间】:2020-06-02 13:55:12
【问题描述】:
我有 ngrx 应用程序,我无法通过我在组件中发送的有效负载从效果中的选择器获取值。
我写了一个我处理的示例代码:
这是我的状态,里面有一个简单的 docs 数组。
export const initialState = {
docs: [{ id: 1, name: "doc1" }, { id: 2, name: "doc2" }]
};
export const reducer = createReducer(
initialState,
);
我不对这个问题采取任何行动,这不是问题。
在我的组件中,我使用选择器获取数组:
docs$ = this.store.pipe(select(fromStore.getAllDocs));
{{docs$ | async | json}}
减速器:
export const selectDocsState = createFeatureSelector("docs");
export const selectDocsStatusState = createSelector(
selectDocsState,
state => state["docs"]
);
export const getAllDocs = createSelector(
selectDocsStatusState,
getDocs
)
我还有一个通过 id 获取的选择器:
{{docsById$ | async | json }}
docsById$ = this.store.pipe(select(fromStore.getById, { id: 1 }));
在减速器中:
export const getById = createSelector(
selectDocsStatusState,
getDocs,
(state, docs, props) => {
console.log({ props });
return docs.docs.docs.filter(d => d.id === props.id);
}
)
到目前为止一切都很好。我得到 docs 数组并显示它。
现在,在我的组件中,我调度了一些动作并按效果捕获:
this.store.dispatch({ type: 'GET_DOC', payload: { id: 2 } });
实际上我想知道这个 id 是否在商店中。
所以我使用来自 rxjs 的 withLatestFrom 和 getById 选择器。
withLatestFrom((a: any) =>
this.store.pipe(select(fromDocs.getById, { id: a.payload.id }))
),
问题是我没有从选择器中获取值,而是我获取了商店实例。
tap(v => {
console.log({ v });
}),
完整效果:
getDoc$ = createEffect(() =>
this.actions$.pipe(
ofType("GET_DOC"),
map(a => a),
tap(a => {
console.log({ a });
}),
withLatestFrom((a: any) =>
this.store.pipe(select(fromDocs.getById, { id: a.payload.id }))
),
tap(v => {
console.log({ v }); // <--------------- HERE SHOULD BE THE DOC AND THE ACTION.PAYLOAD, v[0].a.payload, v[1].id
}),
exhaustMap(payload => {
return of({ type: "SOME_ACTION", payload: null });
})
)
);
Here is my full example in stackbliz.
我在这里错过了什么?
【问题讨论】:
-
this github issue 和 relevant docs 可能有用