Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse error body in Angular 2

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

This is the image of the API return: enter image description here

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:

err.status,err,url,error.statusText

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

like image 459
Sydney Loteria Avatar asked Oct 16 '16 06:10

Sydney Loteria


1 Answers

Your catch is actually receiving a Response. You can access its details with 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

like image 106
BeetleJuice Avatar answered Nov 03 '22 08:11

BeetleJuice