当出现404错误时,如何获取帖子json?

Eur*_*e01 7 javascript typescript angular

我有一个服务调用,当它返回404错误时,我想显示当状态为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;});
Run Code Online (Sandbox Code Playgroud)

出错时,它会设置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>
Run Code Online (Sandbox Code Playgroud)

这是我直接尝试访问api端点时回发的json:

{  
   "_transactionNumber":null,
   "_order":null,
   "_errorDetails":{  
      "_status":"404",
      "_message":"Number is not available"
   }
}
Run Code Online (Sandbox Code Playgroud)

我绑定到从服务调用中返回的transactionResponse对象.不幸的是,尽管我认为这应该有效,但我得到的问题是_errorDetails未定义,因此没有任何显示.

我想知道这是否适合这样的设置?如果现在,我该如何解决?

谢谢!

编辑:重复SO帖子没有答案:如何从Angular 4/2中的后端读取自定义错误消息

jos*_*ish 7

来自服务器的响应主体应该errorerror回调中返回的错误响应的属性中.

关于HttpErrorResponse,文档说明:

  • 表示错误或失败的响应,可能来自非成功的HTTP状态,执行请求时的错误,或者在解析响应期间发生的其他故障.
  • Observable响应流上返回的任何错误都将包含在一个中HttpErrorResponse,以便在发生错误时提供有关HTTP层状态的其他上下文.error属性将包含一个包装Error对象或从服务器返回的错误响应.

如果你想使用相同的transactionResponse显示错误,那么分配error的财产err是回来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;
  });
Run Code Online (Sandbox Code Playgroud)

HTML 然后这将工作.

<input #inputtedNumber class="transactionInput" placeholder="{{ numberPlaceholder | translate }}"/>
<div class="error-msg1" *ngIf="displayErrors" style="margin-left:90px;" name="errorMsg">
    {{transactionResponse._errorDetails._message}}
</div>
Run Code Online (Sandbox Code Playgroud)

2017年9月对Angular的这一部分做了一些工作.为responseType"json"解析错误响应主体所以你可能需要根据你的版本更新Angular.

该解决方案在以下方面进行了测试:

  • 节点v8.2.1
  • NPM v5.3.0
  • Angular CLI:1.7.2
  • 角度:5.0.0

编辑:StackBlitz示例

HttpErrorResponse StackBlitz示例

此示例对服务的外观以及调用的端点进行了一些假设.该服务POST拨打电话www.google.com.这失败并返回一个HttpErrorResponse.

{
  "isTrusted": true
}
Run Code Online (Sandbox Code Playgroud)

error属性HttpErrorResponse被分配给this._transactionResponse.然后可以在模板中访问它并在浏览器中显示.