首页 > 解决方案 > 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 在第一次函数调用和错误返回时不是“更新失败”,即使它应该是。

谢谢

标签: angularhttp.client

解决方案


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 函数返回所需的字符串。


推荐阅读