首页 > 解决方案 > 添加条件以停止 flatmap 的第二次 HTTP 调用

问题描述

我在确定在 PUT 请求中放置条件的位置时遇到问题。为了更新电子邮件,用户必须通过您可以在 getUserInfo() 中看到的 id 和电子邮件测试。我试图将结果的布尔值传递给第二个函数以保释,如果结果为假,则不尝试 PUT 请求而不重新加载页面,因为我不想更新验证失败的信息。无论我在哪里放置条件语句

return this.getUserInfo(this.userId, oldEmail, newEmail, result)

我得到一个错误。感谢您的帮助!

   getUserInfo(id: string, oldEmail: string, newEmail: string, result: boolean) {
    return this.http.get(`http://localhost:3000/api/user/${id}`)
      .pipe(
        tap(value => 'output: ' + "TEST" + value),
        tap(res => {
          if (this.userId === res["posts"]._id && oldEmail === res["posts"].email) {
            console.log("You passed the id and email test");
            result = true;
          }
          else {
            result = false;
            console.log("You failed the test!");
            return;
          }
        })
      );
  }

  updateUserEmail(id: string, oldEmail: string, newEmail: string, result: boolean) {


    const updateEmail: UserEmailChange = {
      id: id, oldEmail: oldEmail, newEmail: newEmail
    };

    return this.getUserInfo(this.userId, oldEmail, newEmail, result)

      .pipe(

        flatMap(userInfo =>

          this.http.put(`http://localhost:3000/api/user/`, id))
      );
  }

标签: angulartypescript

解决方案


你可以抛出一个错误:

return this.http.get(`http://localhost:3000/api/user/${id}`)
    .pipe(
    mergeMap(res => {
          if (this.userId === res["posts"]._id && oldEmail === res["posts"].email) {
          console.log("You passed the id and email test");
          throwError({error: 'not found'});
        }
        else {
          return of(true);
        }
    })
    );
}

当你调用它时:

return this.getUserInfo(this.userId, oldEmail, newEmail, result)
.pipe(
    flatMap(userInfo => this.http.put(`http://localhost:3000/api/user/`, id))
);

然后在可以时捕获错误updateUserEmail

this.updateUserEmail(id, oldEmail, newEmail, result).subscribe(
  result => console.log('worked'),
  error => console.log(error)
);

推荐阅读