使用Redux Observable取消请求不起作用

时间:2018-11-27 21:55:45

标签: javascript rxjs middleware redux-observable side-effects

我正在尝试使用redux-observable在请求中添加取消。尝试实现一个简单的登录示例。目前,添加取消后,我无法再次提交登录请求。

const loginUserApiCall = (username, password) => {
  return new Promise((resolve, reject) => {
    if (username === "foo" && password === "foo") {
      resolve({
        user: { name: "foo", lastName: "fooLName", email: "foo@gmail.com" }
      });
    }
    reject({ err: "Creds are incorrect" });
  });
};

const loginRequestEpic = (action$, state$) =>
  action$.pipe(
    ofType(LOGIN_REQUEST),
    mergeMap(action => {
      const { username, password } = action.payload;
      return loginUserApiCall(username, password);
    }),
    mergeMap(res => of(loginSuccess(res))),
    takeUntil(action$.pipe(ofType(LOGIN_CANCELLED))),
    catchError(err => {
      return of(loginFailure(err))
    })
  );

我做错了什么,因为未发生取消,并且取消后无法重试请求吗?用户取消后,我应该可以重试。

1 个答案:

答案 0 :(得分:1)

一旦执行takeUntil,它将完成您的可观察性,因此,当抛出错误并且整个流被停用时,也是如此。您可以在末尾添加repeat运算符

  action$.pipe(
    ofType(LOGIN_REQUEST),
    mergeMap(action => {
      const { username, password } = action.payload;
      return loginUserApiCall(username, password);
    }),
    mergeMap(res => of(loginSuccess(res))),
    takeUntil(action$.pipe(ofType(LOGIN_CANCELLED))),
    catchError(err => {
      return of(loginFailure(err))
    }),
    repeat()
  );