如何使用redux-observable和axios取消api请求

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

我在我的反应项目中使用了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'
      }))
    )
  })
)
reactjs axios redux-observable
1个回答
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'
      }))
    )
  })
)
© www.soinside.com 2019 - 2024. All rights reserved.