如何使用Redux-observable和Axios取消API请求

时间:2018-11-22 06:11:50

标签: reactjs axios redux-observable

我在我的React项目中使用redux-observable和axios。我想在调用同一操作时取消api请求。但是我下面的代码似乎并没有取消请求。

    const testEpic = action$ => action$.pipe(
  ofType('PUT_ACTION'),
  mergeMap(action => {
    return fromPromise(
      axios({
        url: 'apiUrl',
        data: {},
        method: 'put',
        headers : getHeaders().toObject(),
      })
    )
    .pipe(
      flatMap(response => ({
        data,
        type: 'PUT_ACTION_SUCCESS',
      })),
      takeUntil(action$.pipe(
        filter(action => action.type === 'PUT_ACTION')
      )),
      catchError(error => ({
        error: error.response,
        type: 'PUT_ACTION_ERROR'
      }))
    )
  })
)

1 个答案:

答案 0 :(得分:0)

axios不会自动取消请求。因此,必须编写一个CancelToken。 https://github.com/axios/axios#cancellation

const testEpic = action$ => action$.pipe(
  ofType('PUT_ACTION'),
  mergeMap(action => {
    const CancelToken = axios.CancelToken;   //cancelToken
    const source = CancelToken.source();     //cancelToken
    return fromPromise(
      axios({
        url: 'apiUrl',
        data: {},
        method: 'put',
        headers : getHeaders().toObject(),
        cancelToken: source.token            //this added
      })
    )
    .pipe(
      flatMap(response => ({
        data,
        type: 'PUT_ACTION_SUCCESS',
      })),
      takeUntil(action$.pipe(
        filter(action => action.type === 'PUT_ACTION’),
        tap(ev => source.cancel('canceled'))      //do cancel with message
      )),
      catchError(error => ({
        error: error.response,
        type: 'PUT_ACTION_ERROR'
      }))
    )
  })
)