RXJS:条件可观察的管道

时间:2020-08-26 12:27:12

标签: angular rxjs observable reactive-programming

我在网站上发布了创建团队的请求,并提出了为我的团队上传头像的请求。

在团队创建表单中,有一个头像上传字段。

用户提交表单后,将发送创建请求,在这里,我需要将头像上传请求传递给它,并使用从第一个(团队创建)请求中返回的服务器。仅当头像不为空时(如果用户上传了头像)。

所以我想要这样的东西(this.team是TeamService):

    this.team.createTeam(teamRequest)
    .pipe(
        flatMap(next => this.team.uploadAvatar(next.uuid, avatar)), // if avatar !== null
        catchError(() => {
            this.onError();
            return EMPTY;
        })
    ).subscribe(next => {
        enter code here...
    });

2 个答案:

答案 0 :(得分:1)

只需使用filter运算符,如下所示:

this.team.createTeam(teamRequest)
  .pipe(
    filter(() => avatar),
    flatMap(next => this.team.uploadAvatar(next.uuid, avatar)),
    catchError(() => {
      this.onError();
      return EMPTY;
    })
  )
  .subscribe(next => {
    enter code here...
});

答案 1 :(得分:1)

您能这样子吗?

this.team.createTeam(teamRequest)
  .pipe(
    flatMap(next => avatar ? this.team.uploadAvatar(next.uuid, avatar) : EMPTY),
    catchError(() => {
      this.onError();
      return EMPTY;
    })
  )
  .subscribe(next => {
    enter code here...
});