【问题标题】:How to parse error message sent from server in Angular Component?如何在 Angular 组件中解析从服务器发送的错误消息?
【发布时间】:2018-09-07 08:04:41
【问题描述】:

这是我的后端代码

if (err)
            {
              res.status(400).send({ error: "invalid credentials", data: null, message: "Invalid Credentials" });

            }
            else
            {

                res.status(200).send({ data: user });
            }

这是我的 Angular 代码

 let obj = { "name": name, "email": email, "password": password };

  this.http.post("https://localhost:3000/register",obj, {responseType: 'json'})
    .subscribe(
        data => {
            console.log("POST Request is successful ", data);
        },
        error => {

            console.log(error); 

        }
    );

我能够记录错误对象。我需要获取从后端传递的确切错误消息。

像这样的

 console.log(error.message); 

我试过了,但我得到了一个错误。在Angular JS中解析HttperrorResponse的正确方法是什么?

【问题讨论】:

  • 你能从控制台发布错误吗?

标签: angular http-post


【解决方案1】:

这是我的代码中运行良好的示例:

this.protocolListService.versionWorkspaceId
      .subscribe(res => {
        if(!!res){
          this.projectService.getGeoJsonFromWorkspaceId(res)
          .subscribe(
            res => {
              if(!!res){
                this.editElements = JSON.parse(res.body.pgjGeojson);
              }
            },
            err => {
              console.log("Error > " + err);
              this.editElements = new Workspace();
            },
            () => console.log("Unspecified error")
          );
        }
      });

我认为您应该将error 改为err

【讨论】:

  • 用 err 改变错误 --> 它只是一个回调,它可以是任何东西
【解决方案2】:

只需检查错误是否属于实例类型 HttpErrorResponse 并解析

this.http.post("https://localhost:3000/register",obj, {responseType: 'json'})
        .subscribe(
            data => {
                console.log("POST Request is successful ", data);
            },
            error => {
              if (error instanceof HttpErrorResponse) {
                console.log('message', error.message);
              }
            }
        );

【讨论】:

    【解决方案3】:

    只需使用console.log(error.error.message) 记录实际的错误消息。

    参考:HttpErrorResponse

    【讨论】:

      猜你喜欢
      • 2023-03-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-06-29
      • 2011-10-24
      • 1970-01-01
      • 2014-12-31
      • 2017-05-26
      相关资源
      最近更新 更多