【问题标题】:RxJS Multiple conditional callsRxJS 多个条件调用
【发布时间】:2021-01-04 02:17:30
【问题描述】:

我对 RxJS 中的条件调用有疑问。 场景是我在 forkjoin 中有多个 HTTP 调用。但是在调用内部可能存在依赖关系,例如我从第一次调用中得到一个布尔值,如果这是真的,则应该触发第二次调用。 这是我现在的代码:
 service.method(parameters).pipe(
  tap((data: boolean) => {
    foo.bar= data;
  }),
  concatMap(() =>
    service
      .method(parameters)
      .pipe(
        tap((data: KeyValue<number, string>[]) => {
          if (true) {
            foo.foo = data;
          }
        })
      )
  )
)

我遇到的问题是该方法现在总是被调用。我的目标是只在参数为真时调用该方法,以减少调用量。我希望有人可以帮助我。

【问题讨论】:

    标签: javascript typescript rxjs


    【解决方案1】:

    你可以试试这样的

    service.method(parameters).pipe(
      tap((data: boolean) => {
        foo.bar= data;
      }),
      concatMap((data) => data ? // you pass data as parameter and check if true
        service  // if data is true you return the Observable returned by the service method
          .method(parameters)
          .pipe(
            tap((data: KeyValue<number, string>[]) => {
              if (true) {
                foo.foo = data;
              }
            })
          ) :
        of(false) // if data is false you return an Observable containing what you decide it to contain, in this case 'false' but it could be everything
      )
    )
    

    这个想法是你第一次调用service.method,将这个调用的结果传递给concatMap,然后你根据传递给concatMap的参数决定是否再次调用service.method和返回它返回的 Observable 或返回您在 concatMap 中创建的 Observable,包装您想要的任何值。

    【讨论】:

    • 太棒了,我在发布这个问题 10 分钟后就使用了它,但很高兴看到另一个人也会这样做。谢谢你的回答!
    猜你喜欢
    • 2019-03-21
    • 1970-01-01
    • 1970-01-01
    • 2019-02-09
    • 2021-05-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-25
    相关资源
    最近更新 更多