Angular 如何捕获post请求中失败的http

Angular 如何捕获post请求中失败的http,angular,typescript,ionic-framework,Angular,Typescript,Ionic Framework,在我的服务中,我通过以下方式调用API: async check\u initial\u cpf(cpf:string){ 返回这个.http.post(environment.api_url+'/check_initial_cpf',{},{cpf:cpf}).toPromise(); } 因此,在我的页面中,我以这种方式调用该服务: const check\u cpf=wait this.cnhService.check\u initial\u cpf(this.form\u cpf);

在我的服务中,我通过以下方式调用API:

async check\u initial\u cpf(cpf:string){
返回这个.http.post(environment.api_url+'/check_initial_cpf',{},{cpf:cpf}).toPromise();
}
因此,在我的页面中,我以这种方式调用该服务:

const check\u cpf=wait this.cnhService.check\u initial\u cpf(this.form\u cpf);
如果(检查cpf['error']==true){
presentaleror();
}否则{
console.log('it worked');
}
这是用来捕获内容为
{'error':'api error message}

但当HTTP请求因其他原因(如404500等)失败时,不会发生任何事情


如何以干净的方式执行此操作?

将其包装在
试一下
/
捕获
块中。在这种情况下,
catch
块中可能会出现错误:

try {
  const check_cpf = await this.cnhService.check_initial_cpf(this.form_cpf);
  if (check_cpf['error'] == true) {
    presentAlertError();
  } else {
    console.log('it worked');
  }
} catch(error) {
  presentAlertError();
}
更新 由于您正在使用
HttpClient
进行API调用,因此首先将
observeable
转换为promise,然后在
catch
块中捕获错误是没有意义的

您可以使用捕获错误,然后使用将其返回给调用方。这样,您就可以在提供给
subscribe
方法的第二个回调中捕获它

大概是这样的:

check_initial_cpfObservable(something) {
  return this.http
    .get("your-url-here")
    .pipe(catchError(error => throwError(error)));
}
然后在组件中:

this.cnhService.check_initial_cpfObservable(this.form_cpf)
  .subscribe(
    response => console.log('It Worked in Observable!'),
    error => this.presentAlertError()
  )

以下是两种方法的参考


我个人将使用操作员处理可观察到的错误:

async check\u initial\u cpf(cpf:string){
返回此文件。http
.post(environment.api_url+“/check_initial_cpf”,{},{cpf:cpf})
.pipe(catchError(this.handleError()))
.toPromise();
}
私有句柄错误(){
返回(错误:任意):可观察=>{
console.error(error);//登录到console或处理您的错误
//通过返回空结果让应用程序继续运行。
//或者您可以返回一个可观察到的自定义错误
返回空;
};
}

因此,如果您想捕获请求中的错误,一个示例可以是:

this.http.post(environment.api_url+'/check_initial_cpf', {}, {cpf:cpf}).toPromise().catch(err=>{
  console.error(err)
});
在catch方法中,您可以处理不同的错误。
更多信息:或

您的服务返回一个可观察的(或必须这样做)。在您的组件中,您可以处理错误,以便:

await this.cnhService.check_initial_cpf(this.form_cpf).subscribe(result => {
// do something with your result (status Code 2xx)
}, err => {
// handle error,
// example: console.log(err.message);
});

首先,我要说的是,不利用反应性观测是一种耻辱,但这是你的选择

现在,关于您的问题:当您使用wait for同步行为时,您需要用一个经典的try-catch组来包装您的呼叫,以便处理承诺拒绝

我希望这对你有点帮助