Angular 4/5 HttpClient Http failure during parsing Error
When upgrading my Ionic 3 app to 3.9.0 I also took the opportunity to update the older Http provider to the highly touted HttpClient one. For the most part this worked well and saved some nasy stuff I had in every one of my calls to force it to a JSON response and add the AuthHeader, as the old Http provider didn’t support interceptors. But I did run into a problem:
After some quick googling the issue appears to be when you have a 2xx response from a web server with an empty body tag. For example if your save data to the server and using the Http Status Code 201 to let the client know it was added, instead of having a response object, you will get this error when using HttpClient in Angular 4 and Angular 5.
You can fix it by adding a text type to each call, but that is a really awful way of doing it. But compeek’s reply to this issue has a temp fix, an interceptor!
import { Injectable, NgModule } from '@angular/core'; import { Observable } from 'rxjs/Observable'; import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest, HttpErrorResponse, HttpResponse } from '@angular/common/http'; import { HTTP_INTERCEPTORS } from '@angular/common/http'; @Injectable() export class EmptyResponseBodyErrorInterceptor implements HttpInterceptor { intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { return next.handle(req) .catch((err: HttpErrorResponse) => { if (err.status >= 200 && err.status < 300) { const res = new HttpResponse({ body: null, headers: err.headers, status: err.status, statusText: err.statusText, url: err.url }); return Observable.of(res); } else { return Observable.throw(err); } }); } } @NgModule({ providers: [ { provide: HTTP_INTERCEPTORS, useClass: EmptyResponseBodyErrorInterceptor, multi: true } ] }) export class HttpInterceptorModule { }
You can then import HttpInterceptorModule into the App’s Module, problem solved! Hopefully they will get a fix into the Angular HttpClient soon and we can all remove this workaround but until then….
If you’re a First Responder or know one check out Resgrid which is a SaaS product utilizing Microsoft Azure, providing logistics, management and communication tools to first responder organizations like volunteer fire departments, career fire departments, EMS, search and rescue, CERT, public safety, disaster relief organizations.
One thought on “Angular 4/5 HttpClient Http failure during parsing Error”
Comments are closed.