首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Angular 8 http修补程序已成功完成,但首次未提供正确的响应

Angular 8 http修补程序已成功完成,但首次未提供正确的响应
EN

Stack Overflow用户
提问于 2021-02-24 09:31:35
回答 2查看 158关注 0票数 1

我在Angular 8的一个服务中的函数中有一个http补丁调用:

代码语言:javascript
运行
复制
// 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;
}

此服务函数由组件调用:

代码语言:javascript
运行
复制
save(response: Response): string {
        this.returnStr = this.dataservice.updateResponse(response, this.reviewId);
        console.log("this.returnStr = " + this.returnStr);
    }

this.returnStr被打印在html的顶部。

那么,当第一次单击"Save“按钮时会发生什么--在控制台中:

代码语言:javascript
运行
复制
this.returnStr = 
Success updating response
Patch call for response complete

此后,在控制台中:

代码语言:javascript
运行
复制
this.returnStr = Success updating response
Success updating response
Patch call for response complete

所以http.patch运行得很好,我唯一关心的是this.returnStr的值,它显示在html页面上。如何才能使this.returnStr即使在第一次函数调用时也是“成功更新响应”,而不是空字符串?或者,为什么在第一次调用之后它仍然是一个空字符串?同样的模式也会发生在出现错误的情况下--在第一个函数调用和错误返回时,this.returnStr并不是“更新失败”,即使它应该是“更新失败”。

谢谢

EN

Stack Overflow用户

回答已采纳

发布于 2021-02-24 10:32:51

http.patch是一个异步调用。如果您没有等待补丁调用完成就从updateResponse方法返回字符串,那么您很可能会看到这样的行为。

您应该从updateResponse返回observable

代码语言:javascript
运行
复制
updateResponse(response: Response, reviewId: number): string {
    return this.http.patch(`/assessing/api/reviews/update/${reviewId}`, response, this.httpOptions);
}

修改组件方法,如

代码语言:javascript
运行
复制
 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函数返回所需的字符串。

票数 2
EN
查看全部 2 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66343420

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档