angular - 添加条件以停止 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))
);
}
解决方案
你可以抛出一个错误:
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)
);
推荐阅读
- python - 为什么我不能在带有格式说明符的 f 字符串表达式周围使用空格?
- .net-core - dotnet 恢复钩子脚本?
- c++ - 参数化类的别名(或类型定义)内部类
- asp.net-mvc - ASP.NET 身份密码重置令牌
- java - 我可以使用自定义类作为 api 端点正文输入吗
- javascript - JS,将参数传递给回调函数(必应地图)
- arrays - 如何快速初始化
- java - 如何在 Selenium 中执行 WebElement#click() 之前检查是否存在重叠元素
- python - 从 POST 请求接收 JSON 响应
- excel - 如何在 Excel 中将日期格式 19000101 更改为 01.01.1900?