Analysis error body in Angular 2

I would like to ask if I can analyze the body of the error that the API returns to me.

This is the API return image: enter image description here

Here is 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 URL, status, statusText, etc. using this:

 err.status,err,url,error.statusText 

My problem is that I cannot get the value of the error body.

+5
source share
1 answer

Your catch actually gets a Response . You can access its details using 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 for the @angular/http library. Starting with Angular 5, this library is deprecated in favor of @angular/common/http

+11
source

Source: https://habr.com/ru/post/1258280/


All Articles