如何解析Angular Component中从服务器发送的错误消息?

问题描述 投票:0回答:3

这是我的后端代码

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

            }
            else
            {

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

这是我的Angular Code

 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
3个回答
0
投票

这是我的代码工作正常的一个例子:

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


0
投票

只需检查错误是否为实例类型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);
              }
            }
        );

0
投票

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

参考:HttpErrorResponse

© www.soinside.com 2019 - 2024. All rights reserved.