我在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的顶部。
那么,当第一次单击"Save“按钮时会发生什么--在控制台中:
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并不是“更新失败”,即使它应该是“更新失败”。
谢谢
发布于 2021-02-24 10:32:51
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函数返回所需的字符串。
https://stackoverflow.com/questions/66343420
复制相似问题