微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在 RxJS + Redux + Axios 中调度多个动作

如何解决在 RxJS + Redux + Axios 中调度多个动作

我正在创建一个登录史诗并分派多个操作,多个操作在“CatchError”内分派得很好,但会产生错误“操作必须是普通对象。使用自定义中间件进行异步操作。”当在 'else' 块中的 observable 中分派动作时。

export const loginUserEpic = action$ =>
action$.pipe(
    ofType(LOGIN_USER),switchMap(({ payload: { email,password } }) => {
      const body = {
        email: email,password: password
      };

  return from(axios.post(`${process.env.REACT_APP_BACKEND}/api/auth/login`,body,config)).pipe(
    map(response => {
      if (response.data.user.is_active) {
        return { type: "LOGIN_SUCCESS",payload: response.data };
      } else {
        return of(
          { type: "USER_LOADING" },{ type: "TOGGLE_MODAL" },updateModalData(modalTypes.EMAIL_SENT,"")
        );
      }
    }),catchError(err =>
      of({ type: "LOGIN_FAIL" },createalert(alertTypes.RED_ALERT,err.data,err.status))
    )
  );
}));

解决方法

我使用了mergemap,所以我可以返回一个observable:

    export const loginUserEpic = action$ =>
  action$.pipe(
    ofType(LOGIN_USER),switchMap(({ payload: { email,password } }) => {
  const body = {
    email: email,password: password
  };

  return from(axios.post(`${process.env.REACT_APP_BACKEND}/api/auth/login`,body,config)).pipe(
    mergeMap(response => {
      if (response.data.user.is_active) {
        return of({ type: "LOGIN_SUCCESS",payload: response.data });
      } else {
        return of(
          { type: "USER_LOADING" },{ type: "TOGGLE_MODAL" },updateModalData(modalTypes.EMAIL_SENT,"")
        );
      }
    }),// takeUntil(actions$.pipe(ofType(CANCEL))),catchError(err =>
      of({ type: "LOGIN_FAIL" },createAlert(alertTypes.RED_ALERT,err.data,err.status))
    )
  );
})

);

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。