Angular 从 c# 接收到 StatusCode 对象时意外触发 catchError
Angular catchError firing unexpectedly when received StatusCode object from c#
我有一个正在 C# 后端工作的 API 调用,但 Angular 前端似乎将 C# 回复视为错误。请注意,对象的文本是 'comment added',表示已发回 200 OK 响应。为什么会触发catchError函数?
C# 方法:
[HttpPost("AddComments")]
public ActionResult<string> AddComment(BillingComments b)
{
try
{
return StatusCode(200, "comment added");
}
catch (Exception e)
{
return StatusCode(500, "error adding comment");
}
}
Angular方法:
submitComment(newComment: BillingComments): any {
return this.http.post('/api/BillingLg/AddComments', newComment)
.pipe(catchError(this.appSvc.handleError<string>('submitComment', 'comment submitting err')));
}
appSvc.handleError返回的错误:
Service error: submitComment failed
Msg: Http failure during parsing for http://localhost:49975/api/BillingLg/AddCommentsStatus: 200Detail: {"error":{},"text":"comment added"}Text: OK & return type specified (failed gracefully)
Angular 默认解析来自 API 的响应到对象,因此默认情况下,它期望 JSON 字符串是 return 来自 [=19] =].
所以你有两个选择,要么 return a JSON 而不是字符串(推荐),比如
return StatusCode(200, "{\"status\": \"comment added\"}");
或者您可以让 HttpClient 期望字符串被 returned:
this.http.post('/api/BillingLg/AddComments', newComment, {responseType: 'text'})
.pipe(catchError(this.appSvc.handleError<string>('submitComment', 'comment submitting err')));
我有一个正在 C# 后端工作的 API 调用,但 Angular 前端似乎将 C# 回复视为错误。请注意,对象的文本是 'comment added',表示已发回 200 OK 响应。为什么会触发catchError函数?
C# 方法:
[HttpPost("AddComments")]
public ActionResult<string> AddComment(BillingComments b)
{
try
{
return StatusCode(200, "comment added");
}
catch (Exception e)
{
return StatusCode(500, "error adding comment");
}
}
Angular方法:
submitComment(newComment: BillingComments): any {
return this.http.post('/api/BillingLg/AddComments', newComment)
.pipe(catchError(this.appSvc.handleError<string>('submitComment', 'comment submitting err')));
}
appSvc.handleError返回的错误:
Service error: submitComment failed Msg: Http failure during parsing for http://localhost:49975/api/BillingLg/AddCommentsStatus: 200Detail: {"error":{},"text":"comment added"}Text: OK & return type specified (failed gracefully)
Angular 默认解析来自 API 的响应到对象,因此默认情况下,它期望 JSON 字符串是 return 来自 [=19] =].
所以你有两个选择,要么 return a JSON 而不是字符串(推荐),比如
return StatusCode(200, "{\"status\": \"comment added\"}");
或者您可以让 HttpClient 期望字符串被 returned:
this.http.post('/api/BillingLg/AddComments', newComment, {responseType: 'text'})
.pipe(catchError(this.appSvc.handleError<string>('submitComment', 'comment submitting err')));