首页 > 解决方案 > 如何获得失败 api 的响应

问题描述

在我的 api 中,有一些验证失败,并在我的网络选项卡响应中给我错误,如下所示:

{"Message":"not allowed '<' word;"}

但我无法在订阅方法的错误块中显示它。当 api 失败或响应状态代码为 400 时,我如何在我的 toastr 上显示这个。我试过这个:

this.myService
      .saveData(myData)
      .pipe(takeUntil(this.unsubscribe))
      .subscribe(
        data => {
          this.alertService.success('Record Saved Successfully');
        },
        error => {
          this.spinner.hide();
          this.alertService.error(error.Message);
        }
      );
  }


 private handleError(error: HttpErrorResponse, scope) {
    if (error.error instanceof ErrorEvent) {
      console.error('An error occurred:', error.error.message);
    } else {
      console.error(
        `Backend returned code ${error.status}, ` +
        `body was: ${error.error}`);
    }
    return throwError(
      'Something bad happened, please try again later.');
  }

标签: javascriptangulartypescript

解决方案


根据角度文档,这种更改应该有效。

创建自定义错误处理程序或使用默认值

 private handleError(error: HttpErrorResponse, scope) {
    if (error.error instanceof ErrorEvent) {
      console.error('An error occurred:', error.error.message);
    } else {
      console.error(
        `Backend returned code ${error.status}, ` +
        `body was: ${error.error}`);
    }
    return throwError(
      'Something bad happened, please try again later.');
  }

然后导入并使用:

import { catchError } from ...

...
...
this.myService
      .saveData(myData)
      .pipe(takeUntil(this.unsubscribe))
      .pipe(catchError(this.handleError)).
      .subscribe(
        data => {
          this.alertService.success('Record Saved Successfully');
        }
      );
  }

推荐阅读