首页 > 解决方案 > TypeError: Object(...)(...).flatMap 不是函数

问题描述

请你能帮我解释为什么会出现这个错误吗?

在此处输入图像描述

import { FETCHING_DATA } from '../constants'
import { getDataSuccess, getDataFailure } from './actions'
import getPeople from '../api'

import { from, Observable, of} from 'rxjs';
// import 'rxjs'
// import { Observable } from 'rxjs/Observable';
import { mergeMap } from 'rxjs/operators';
import { ofType } from 'redux-observable';

// const fetchUserEpic = action$ =>
//   action$.ofType(FETCHING_DATA)
//     .mergeMap(action =>
//       Observable.fromPromise(getPeople())
//         .map(response => getDataSuccess(response))
//         .catch(error => Observable.of(getDataFailure(error)))
//       )

const fetchUserEpic = action$ =>
  action$.pipe(  //fixed
    ofType(FETCHING_DATA),
    mergeMap(action => {
      return from(getPeople())
        .flatMap(payload => [
          {
            type: 'SIGNUP_CONCIERGE_SUCCESS',
            payload
          }
        ])
        .catch(error =>
          of({
            type: 'SIGNUP_CONCIERGE_ERROR',
            payload: { error }
          })
        );
    })
  );

export default fetchUserEpic

标签: reactjsreduxrxjs

解决方案


这是来自 redux-observable 的示例

import { ajax } from 'rxjs/ajax';

const fetchUserEpic = action$ => action$.pipe(
  ofType(FETCH_USER),
  mergeMap(action => ajax.getJSON(`/api/users/${action.payload}`).pipe(
    map(response => fetchUserFulfilled(response)),
    catchError(error => of({
      type: FETCH_USER_REJECTED,
      payload: error.xhr.response,
      error: true
    }))
  ))
);

这里是采用的解决方案

import { FETCHING_DATA } from '../constants'
import { getDataSuccess, getDataFailure } from './actions'
import getPeople from '../api'

import { from, of } from 'rxjs';
import { map, catchError, mergeMap } from 'rxjs/operators';
import { ofType } from 'redux-observable';

const fetchUserEpic = action$ => action$.pipe(
  ofType(FETCHING_DATA),
  mergeMap(() => from(getPeople()).pipe(
    map(getDataSuccess),
    catchError(error => of(getDataFailure(error)))
  ))
);

export default fetchUserEpic;

推荐阅读