【问题标题】:How to cancel api request using redux-observable and axios如何使用 redux-observable 和 axios 取消 api 请求
【发布时间】:2019-04-24 18:39:18
【问题描述】:

我在我的 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'
      }))
    )
  })
)

【问题讨论】:

    标签: reactjs axios redux-observable


    【解决方案1】:

    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'
          }))
        )
      })
    )
    

    【讨论】:

      猜你喜欢
      • 2018-12-02
      • 2017-10-14
      • 1970-01-01
      • 1970-01-01
      • 2020-12-29
      • 1970-01-01
      • 2017-12-11
      • 2018-10-14
      • 2017-08-30
      相关资源
      最近更新 更多