无法将forkJoin与redux-observable一起使用

问题描述 投票:0回答:1

[让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中,然后像以前一样对待它。

typescript rxjs redux-observable
1个回答
0
投票

啊我不明白mergeMap。问题是我的responses.map(...)返回了Void[]

所以校正后的块是

          mergeMap(responses => [
            sharedActions.setLoading(false),
            ...responses.map(response =>
              documentActions.fetchSuccess({
                name: response.name,
                data: response.data,
              })
            ),
          ]),
© www.soinside.com 2019 - 2024. All rights reserved.