大佬教程收集整理的这篇文章主要介绍了javascript – 如果出现404错误,如何获取帖子json?,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
好吧,我有这个服务电话:
this._transactionservice.findExisTingtransaction(user,searchnumber) .subscribe(data => { this.transactionResponse = data; console.log(JSON.Stringify(this.transactionResponsE)); this.router.navigate(['/edit-transaction-portal'],{queryParams: {Bill: searchnumber}}); this.onDismiss(); },(err) => { this.displayErrors = true;});
出错时,它会设置bool displayErrors = true然后我可以在我的UI中显示错误消息.
在HTML代码中:
<input #inputtednumber class="transactionInput" placeholder="{{numberPlaceholder | translate }}"/> <div class="error-msg1" *ngIf="displayErrors" style="margin-left:90px;" name="errorMsg"> {{transactionResponse._errorDetails._messagE}} </div>
这是我直接尝试访问api端点时回发的json:
{ "_transactionnumber":null,"_order":null,"_errorDetails":{ "_status":"404","_message":"number is not available" } }
我绑定到从服务调用中返回的transactionResponse对象.不幸的是,尽管我认为这应该有效,但我得到的问题是_errorDetails是未定义的,因此没有任何显示.
我想知道这是否适合这样的设置?如果现在,我该如何解决?
谢谢!
编辑:没有答案的重复SO帖子:How to read Custom error message from backend in Angular 4/2
关于HttpErrorResponse,文件说明:
>表示错误或失败的响应,可能来自非成功的http状态,执行请求时的错误,或者在解析响应期间发生的其他故障.
> Observable响应流上返回的任何错误都将包含在httpErrorResponse中,以便在发生错误时提供有关http层状态的其他上下文. error属性将包含一个包装的Error对象或从服务器返回的错误响应.
如果要使用相同的transactionResponse来显示错误,请分配返回this.transactionResponse的错误的错误属性.
服务电话
this._transactionservice.findExisTingtransaction(user,searchnumber).subscribe( (data) => { this.transactionResponse = data; console.log(JSON.Stringify(this.transactionResponsE)); this.router.navigate(['/edit-transaction-portal'],{queryParams: {Bill: searchnumber}}); this.onDismiss(); },(err: httpErrorResponsE) => { this.displayErrors = true; // assign the error property of the err that comes BACk to the transactionResponse this.transactionResponse = err.error; });
HTML
然后这将工作.
<input #inputtednumber class="transactionInput" placeholder="{{ numberPlaceholder | translate }}"/> <div class="error-msg1" *ngIf="displayErrors" style="margin-left:90px;" name="errorMsg"> {{transactionResponse._errorDetails._messagE}} </div>
2017年9月,Angular的这一部分已经完成了一些工作.parse error response body for responseType “json”因此您可能需要根据您的版本更新Angular.
该解决方案在以下方面进行了测试:
>节点v8.2.1
> NPM v5.3.0
> Angular CLI:1.7.2
> Angular:5.0.0
编辑:StackBlitz示例
HttpErrorResponse StackBlitz example
此示例对服务的外观以及调用的端点进行了一些假设.该服务向www.google.com发出POST呼叫.这会失败并返回httpErrorResponse.
{ "isTrusted": true }
httpErrorResponse的error属性分配给this._transactionResponse.然后可以在模板中访问它并在浏览器中显示.
以上是大佬教程为你收集整理的javascript – 如果出现404错误,如何获取帖子json?全部内容,希望文章能够帮你解决javascript – 如果出现404错误,如何获取帖子json?所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。