首页 > 解决方案 > Angular:无法通过服务捕获 404 API 的消息

问题描述

我想显示 API 返回的状态为 404 的消息,如下所示:

{message: "Email Address does not exists", status: 404, data: null}

这个 API 是用 SpringBoot 语言生成的。

我通过一个service.ts文件在 Angular 8 中调用 API:

forgotPwd(value, bearer) {
  return this.http.put(this.rootUrl + 'api/user/forgot_password', value,  {headers: new HttpHeaders({  Authorization: 'Bearer ' + bearer, 'Content-Type': 'application/json'})});
}

component.ts文件中,我想处理如下情况:

this.commService.forgotPwd(this.submissionArray, this.userToken).subscribe((data: any) => {
  this.rawData = data;
  const result = this.rawData;
  if (result.status !== 200) {
    console.log(result.message);
  } else {
    console.log(result.message);
  }
});

但是,我在控制台中没有看到任何内容。如何在 Angular 中处理 404 / 400 请求,并在上面提到的组件文件中抛出相应的消息?

标签: angular

解决方案


所有的 http 错误都将在错误回调中可用,例如

this.service.getData()
    .subscribe(
      (data) => {}, // success path
      (error: HttpErrorResponse)=> {} // error path
    );

在错误中,您将获得状态和消息。

所以对于你的情况,

this.commService.forgotPwd(this.submissionArray, this.userToken)
.subscribe((data: any) => {
  this.rawData = data;
  const result = this.rawData;
    console.log(result.message);
}, error => {
   console.log('handle error');
});

注意:当 Rest API 返回 4XX 或 5XX 作为响应状态时,上述场景有效。


推荐阅读