【问题标题】:Condition the execution of a flatmap in rxjs - angular 5条件在 rxjs 中执行平面图 - 角度 5
【发布时间】:2019-01-20 09:27:37
【问题描述】:

在 rxjs 中,我想在多个平面图上创建一个条件,因此我不执行第二个和第三个平面图,而是直接转到订阅:

this.authenticationAPI.getUser()
       .flatmap(response1 => if(response1 != null) // I want to go directly to subscribe
       .flatmap(response2 => return observable2(response2))
       .flatmap(response3 => return observable3(response3))
       .subscribe(response 4 => console.log(response4));

我想过将 null observables 传递给第二个和第三个平面图,但还有其他解决方案吗?

【问题讨论】:

    标签: angular rxjs flatmap


    【解决方案1】:

    您应该区分两种情况:使用filter 的失败和成功。这种方式更具声明性,更易于阅读

    const response$ = this.authenticationAPI.getUser();
    
    // failure
    response$
      .filter((res) => !res)
      .subscribe(() => {
        console.log('Unauthentication')
      });
    
    // success
    response$
      .filter((res) => res)
      .flatmap(response2 => return observable2(response2))
      .flatmap(response3 => return observable3(response3))
      .subscribe(response 4 => console.log(response4));
    

    【讨论】:

      【解决方案2】:

      最好稍微嵌套你的平面图——这个例子使用 RxJS 5.5/6“管道”操作符,如果你使用的是 RxJS 的早期版本,你需要稍微翻译一下以映射到旧版本语法(如果需要,请发表评论,我会添加一个示例):

      this.authenticationAPI.getUser().pipe(
          map((response1) => {
              if (response1 != null) return of(response1);
              else return of(response1).pipe(
                  flatMap((response2) => observable2(response2)),
                  flatMap((response3) => observable3(response3))
              )
          })
      ).subscribe(response1or4 => console.log(response1or4));
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-07-31
        • 2016-11-23
        • 1970-01-01
        • 2018-07-25
        • 1970-01-01
        • 2021-10-02
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多