I have an http patch call in a function in a service in Angular 8:
// 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;
}
This service function is called by a component:
save(response: Response): string {
this.returnStr = this.dataservice.updateResponse(response, this.reviewId);
console.log("this.returnStr = " + this.returnStr);
}
this.returnStr gets printed at the top of the html.
So what happens when the "Save" button is clicked for the first time is-- In console:
this.returnStr =
Success updating response
Patch call for response complete
Thereafter, in console:
this.returnStr = Success updating response
Success updating response
Patch call for response complete
So the http.patch works fine, my only concern is the value of this.returnStr, which gets shown on the html page. How can I make it such that even on the first function call, this.returnStr is "Success updating response", not an empty string? Or, why is it still an empty string after the first call? The same pattern happens in the case of an error -- this.returnStr is not "Failed to update" on the first function call and error return, even though it should be.
Thanks
http.patch is a asynchronous call. If you return the string from the updateResponse method without waiting for the patch call to complete then you are likely to see such behavior.
You should return observable from the updateResponse
updateResponse(response: Response, reviewId: number): string {
return this.http.patch(`/assessing/api/reviews/update/${reviewId}`, response, this.httpOptions);
}
Modify component method like
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");
});
There is another way to use pipe and map operator where you can return required string from the updateResponse function.