不能使用 forkJoin with redux-observable



我有点困惑,试图让 rxjs 在这里玩得很好。

我可以很好地执行单个 API 请求,例如


const documentFetchEpic: Epic<TRootAction, TRootAction, TRootState> = (action$, store) =>
action$.pipe(
filter(isActionOf(documentActions.fetch)),
withLatestFrom(store),
switchMap(([action, state]) =>
merge(
of(sharedActions.setLoading(true)),
ApiUtils.documents.fetch(action.payload).pipe(
mergeMap(response => [
sharedActions.setLoading(false),
documentActions.fetchSuccess({
name: action.payload,
data: response,
}),
]),
catchError(err => of(sharedActions.setError(err), sharedActions.setLoading(false)))
)
)
)
);

按预期工作。

问题是当我尝试通过forkJoin一次获取多个项目时。我不太确定该怎么做。

const DocumentTypes = ['a', 'b', 'c'];
const fetchAll = () =>
forkJoin<{ name: TDocumentTypes; data: DocumentRes }>(
...DocumentTypes.map(documentType =>
ApiUtils.documents.fetch(documentType).pipe(map(response => ({ name: documentType, data: response.data })))
)
)
const documentFetchAllEpic: Epic<TApiActions, TApiActions, TApiState> = (action$, store) =>
action$.pipe(
filter(isActionOf(documentActions.fetchAll)),
withLatestFrom(store),
switchMap(([action, state]) =>
merge(
of(sharedActions.setLoading(true)),
fetchAll().pipe(
mergeMap(responses => [
sharedActions.setLoading(false),
responses.map(response => {
documentActions.fetchSuccess({
name: response.name,
data: response.data,
});
}),
]),
catchError(err => of(sharedActions.setError(err), sharedActions.setLoading(false)))
)
)
)
);

这将无法编译,并显示以下错误:

Type 'void[]' is missing the following properties from type 'PayloadAction<"@@api/shared/SET_LOADING", Error>': type, payloadts(2322)

我对 rx 不是很了解.js所以我猜我的问题就在那里。我想将所有 documentFetch Observables 包装成一个forkJoin,然后像以前一样处理它。

啊。我不明白合并地图。问题是我的responses.map(...)回来了Void[]

所以更正的块是

mergeMap(responses => [
sharedActions.setLoading(false),
...responses.map(response =>
documentActions.fetchSuccess({
name: response.name,
data: response.data,
})
),
]),

最新更新