I have an Angular/JHipster application that makes HTTP calls. I want to do error handling in my Observable
subscriptions.
However, when the first time the error handler is invoked, the err
object is not a response, it's a raw {}
Object
. All subsequent error handler invocations have a valid Response
.
Why is this happening, and how do I fix it?
MyComponent.ts:
handleClickPost() {
this.myService.doPost(this.body)
.subscribe(
(res: Response) => {
this.responseOk = true;
},
(err: Response) => {
// This is a HACK!
// For some reason, the first time this error handler is invoked (after page load),
// the response body is empty here and serializes to "{}".
if (JSON.stringify(err) === '{}') {
// first request always reaches here... WHY?
this.handleClickPost(); // NB: workaround
// err.json(); // results in null "method not found" error
} else {
// second request always reaches here... WHY?
// (I want all requests to go here with a valid 'Response' object)
this.showRequestFailed = true;
this.errorResponse = err.json();
}
}
);
}
MyService.ts:
doPost(body): Observable<Response> {
return this.http.post(this.resourceUrl, body);
}
My shoddy workaround is to just call the method again after the first empty-body failure in order to get a typed Response
.
NB: This behavior happens with both Angular 2 and Angular 4.