Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse error return from HTTP catch - Angular 2

I have achieved to get the value of the API error return via catch in my HTTP Request. My problem now is how can I get the return value of the HTTP catch in my component when I call the service.

This is my code in my HTTP service:

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: "xxxx",
                    client_secret: "xxxxx"
                }
            ),
            { headers }
        )
        .map(res => res.json())
        .catch((err:Response) => {
            let details = err.json();
            return Observable.throw(new Error(details));
         });

     }

This is my code in my login.component:

this.loginService.login(this.model.username,this.model.password)
            .subscribe(
                data => console.log("data"),
                error => {
                   console.log(error);
                },
                ()  =>  console.log("Finished")
            );

and in the chrome developer tools this is the return of the console.log:

Error: [object Object](…)

But the actual return of the http service catch is this: { "error":"invalid_credentials","error_description": "invalid credentials" } and this is I want to get in the login.component

like image 716
Sydney Loteria Avatar asked Oct 16 '16 07:10

Sydney Loteria


1 Answers

In your .catch(), change:

return Observable.throw(new Error(details));

to:

return Observable.throw(details);
like image 118
BeetleJuice Avatar answered Nov 04 '22 00:11

BeetleJuice