angular - Angular 8 http补丁成功完成但第一次没有提供正确的响应
问题描述
我在 Angular 8 的服务中的一个函数中有一个 http 补丁调用:
// public returnStr: string = ""; at top of service
updateResponse(response: Response, reviewId: number): string {
this.http.patch(`/assessing/api/reviews/update/${reviewId}`, response, this.httpOptions)
.subscribe(() => {
console.log("Success updating response");
this.returnStr = "Success updating response";
},
response => {
console.log("Error in response patch call: ", response);
this.returnStr = "Failed to update";
},
() => {
console.log("Patch call for response complete");
});
return this.returnStr;
}
此服务函数由组件调用:
save(response: Response): string {
this.returnStr = this.dataservice.updateResponse(response, this.reviewId);
console.log("this.returnStr = " + this.returnStr);
}
this.returnStr 打印在 html 的顶部。
那么当第一次单击“保存”按钮时会发生什么 - 在控制台中:
this.returnStr =
Success updating response
Patch call for response complete
此后,在控制台中:
this.returnStr = Success updating response
Success updating response
Patch call for response complete
所以 http.patch 工作正常,我唯一关心的是 this.returnStr 的值,它会显示在 html 页面上。我怎样才能使它即使在第一次函数调用时, this.returnStr 也是“成功更新响应”,而不是空字符串?或者,为什么第一次调用后它仍然是一个空字符串?同样的模式发生在错误的情况下—— this.returnStr 在第一次函数调用和错误返回时不是“更新失败”,即使它应该是。
谢谢
解决方案
http.patch 是一个异步调用。如果您从 updateResponse 方法返回字符串而不等待补丁调用完成,那么您很可能会看到这种行为。
您应该从 updateResponse 返回 observable
updateResponse(response: Response, reviewId: number): string {
return this.http.patch(`/assessing/api/reviews/update/${reviewId}`, response, this.httpOptions);
}
修改组件方法如
this.dataservice.updateResponse(response, this.reviewId).subscribe (() => {
console.log("Success updating response");
this.returnStr = "Success updating response";
},
response => {
console.log("Error in response patch call: ", response);
this.returnStr = "Failed to update";
},
() => {
console.log("Patch call for response complete");
});
还有另一种使用管道和映射运算符的方法,您可以从 updateResponse 函数返回所需的字符串。
推荐阅读
- netbeans - 尝试使用 Opendaylight 解析 YANG 文件但遇到 SchemaResolutionException
- jms - 在 Wildfly 12 中配置 ActiveMQ Artemis 以在集群中交付时间关键的消息
- python - Int 被读取为文本?Python
- r - 迭代地在 dplyr 中创建多个新的 mutate 列 - 纬度和经度
- python - 在 Python 中比较和均衡两个数据帧
- javascript - 有没有更有效的方法来检查列数?
- react-native - 仅在 componentDidMount 中未定义的道具
- javascript - 多次训练brain.js?
- ios - 如何替换 IPA 文件中的图像
- filter - 过滤系统日志消息 rsyslog ubuntu