代码之家  ›  专栏  ›  技术社区  ›  Noitidart

中游调度行动

  •  1
  • Noitidart  · 技术社区  · 6 年前

    RxJS新手。并且可以观察到redux。

    我有麻烦了,我正试图在中途安排一个行动 of(takeAction()) 在下面的代码中,然后听来自此的响应操作,或者 RESOLVE_TAKE 类型或 REJECT_TAKE of(takeAction)

    除了这个问题之外,还有一个好处:关于如何重构代码的任何风格建议,我都不确定这是否是最干净、最可读的方式。我在拍一部,然后拍一部 switch 在不同的状态码上,然后 res (回程响应)和 reply ,如果可能,将reply转换为json,然后传递 物件 takeAction 采取行动 解决问题 拒绝接受 .

    action$.pipe(
        ofType(START_FOO),
        switchMap({ url } =>
            from(fetch(url)).pipe(
                mergeMap(res => from(res.text()).pipe(
                    mergeMap(reply => {
                        try { reply = JSON.parse(reply) } catch(ignore) {}
                        switch (res.status) {
                            case 200: {
                                return of(takeAction(res, reply)).pipe( // not dispatching
                                    action$.pipe(
                                        ofType(RESOLVE_TAKE, REJECT_TAKE),
                                        mergeMap(({ type }) => {
                                            if (type === RESOLVE_TAKE) {
                                                return of(resolveFooAction())
                                            } else {
                                                return of(rejectFooAction())
                                            }
                                        })
                                    )
                                )
                            }
                            // other res.status cases go here
                        }
                    })
                )
            )
        )
    )
    
    1 回复  |  直到 6 年前
        1
  •  1
  •   seniorquico    6 年前

    问题似乎出在你自己身上 of(takeAction(res, reply)) .pipe(...) . 把你的“采取行动”命令发给那些东西 里面 这个 .pipe

    action$.pipe(
      ofType(START_FOO),
      switchMap({ url } =>
        from(fetch(url)).pipe(
          mergeMap(res => from(res.text()).pipe(
            mergeMap(reply => {
              try {
                reply = JSON.parse(reply)
              } catch (ignore) {
              }
    
              switch (res.status) {
                case 200: {
                  return merge(
                    of(takeAction(res, reply)),
                    action$.pipe(
                      ofType(RESOLVE_TAKE, REJECT_TAKE),
                      map(({ type }) => {
                        if (type === RESOLVE_TAKE) {
                          return resolveFooAction()
                        } else {
                          return rejectFooAction()
                        }
                      }),
                    ),
                  )
                }
                // other res.status cases go here
              }
            })
          )
        )
      )
    )
    

    在上面的例子中 采取行动 用管道输送到任何地方。相反,它被“流”回Redux商店。这个 merge 是一种在创建对动作流的另一个订阅以临时侦听另一个事件的同时将某些内容流出来的方法。