在Angular 2中解析错误体

时间:2021-01-31 17:03:57

I would like to ask if how can I parse the error body that the API return to me.

我想问一下如何解析API返回给我的错误主体。

This is the image of the API return: 在Angular 2中解析错误体

这是API返回的图像:

Here's my code:

这是我的代码:

login(username,password){
        let headers = new Headers();
        headers.append('Content-Type','application/json');

        return this.http.post(this.configEnvironment.url() + "oauth/access_token",
            JSON.stringify(
                {
                    username: username,
                    password: password,
                    grant_type: "password",
                    client_id: "xxxxxxx",
                    client_secret: "xxxxxxxx"
                }
            ),
            { headers }
        )
        .map(res => res.json())
        .catch((err:any) =>{
            console.log(err);
            return Observable.throw(new Error(err));
         });

     }

I can access the URL,status,statusText and etc using this:

我可以使用以下方法访问URL,status,statusText等:

err.status,err,url,error.statusText

My problem is i can't get the value of the error body.

我的问题是我无法获得错误体的价值。

1 个解决方案

#1


11  

Your catch is actually receiving a Response. You can access its details with json()

您的捕获实际上是收到响应。您可以使用json()访​​问其详细信息

import { Response }  from "@angular/http";
...
.catch((err:Response) =>{
            let details = err.json().error;
            console.log(details);
            return Observable.throw(new Error(details));
         });

note: This answer is about the @angular/http library. As of Angular 5, this library is deprecated in favor of @angular/common/http

注意:这个答案是关于@ angular / http库的。从Angular 5开始,不推荐使用这个库,而使用@ angular / common / http

#1


11  

Your catch is actually receiving a Response. You can access its details with json()

您的捕获实际上是收到响应。您可以使用json()访​​问其详细信息

import { Response }  from "@angular/http";
...
.catch((err:Response) =>{
            let details = err.json().error;
            console.log(details);
            return Observable.throw(new Error(details));
         });

note: This answer is about the @angular/http library. As of Angular 5, this library is deprecated in favor of @angular/common/http

注意:这个答案是关于@ angular / http库的。从Angular 5开始,不推荐使用这个库,而使用@ angular / common / http