简体   繁体   English

Angular 素材 dialogRef.afterClosed().subscribe not handle error

[英]Angular material dialogRef.afterClosed().subscribe not handle error

I'm using an angular material modal to call a web service in case of confirme button clicked it's work the problem it's I can't get the error in case of the web service return an error我正在使用 angular 材料模态调用 web 服务,以防单击确认按钮它的工作问题是在 Z2567A5EC9705EB7AC2C984033E 服务返回错误的情况下我无法得到错误

dialogRef.afterClosed().subscribe(result => {

// calling the ws 
 this.reqService.onRequestSave(this.request).subscribe(data =>{

    // do some work
  },err=>{
      // never displayed
      alert(err)
   }
)

},error=>{
     // never displayed
     alert(error)
} 
);

// Rest client // Rest 客户端

 onRequestSave(request : RequestDto){
        console.log(JSON.stringify(request))
        return this.http.post<RequestResponseDto>(this.apiUrl + "/request",JSON.stringify(request),this.utils.getHeaders());
    }

I want to display the first alert any idea how to fix that thanks for any help我想显示第一个警报,知道如何解决这个问题,感谢您的帮助

Why are you trying to call the service in the parent component.你为什么要在父组件中调用服务。 Instead on click of confirmation button, you can have a method that calls the service and if the call is successfully completed, close the dialog and if there is an error, display the error.而不是单击确认按钮,您可以有一个调用服务的方法,如果调用成功完成,关闭对话框,如果有错误,则显示错误。

Maybe something like this.也许是这样的。

In the dialog component:-在对话框组件中:-

onConfirmation(){
  this.reqService.onRequestSave(this.request).subscribe(
    data  => { this.dialog.close(data); },
    error => { alert(error); }
}

and in the parent component:-在父组件中:-

dialog.afterClosed().subscribe(result => {
  this._snackbar.open("Request successfully saved.");
});

What if you try surround that code with try/catch?如果您尝试用 try/catch 包围该代码会怎样? This should work for errors where your 'processing' code throws an error:这应该适用于您的“处理”代码引发错误的错误:

dialogRef.afterClosed().subscribe(result => {
  // calling the ws 
  this.reqService.onRequestSave(this.request).subscribe(data =>{
    try {
      // processing 'data'
    } catch (err) {
      // displayed, if the processing code
      alert(err);
    }
  }, err=>{
    // displayed, if the Observable produces an error
    alert(err);
  });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM