8

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.

1 Answer 1

13

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

Sign up to request clarification or add additional context in comments.

2 Comments

@SydneyLoteria No problem. You'll get better IDE assistance if you change the type of err from any to Response as I've just done.
What's the Angular 5 @angular/common/http method?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.