Http http error message

Is there a way to compare not only a successful answer, but also an error?

I want to get a modified error in the subscription function

request.subscribe( response => { this.user = response; }, error => { this.error = error; } ); 

I already tried this

 let request = this.http.put(url, JSON.stringify(user)) .map( response => response.json(), error => this.handleError(error) // returns a string ); 

but handleError never executed.

Thanks in advance.

+8
angular observable rxjs
source share
1 answer

To display the result of an error response, you need to use the catch statement:

 let request = this.http.put(url, JSON.stringify(user)).map( response => response.json()) .catch( error => this.handleError(error) ); 

The callback specified in the map statement is called only for successful responses.

If you want to "match" the error, you can use something like this:

 this.http.get(...) .map(...) .catch(res => Observable.throw(res.json()) 

In this case, the displayed error will be provided for the callback defined in the second parameter of the subscription method.

+12
source

All Articles