Skip to content

Instantly share code, notes, and snippets.

@henev
Created August 2, 2018 07:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save henev/abce6bd2cf1f59b3ab9799952dbac651 to your computer and use it in GitHub Desktop.
Save henev/abce6bd2cf1f59b3ab9799952dbac651 to your computer and use it in GitHub Desktop.
In some cases API is returning empty response which cannot be parsed to JSON. If we have response type json angular will parse it automatically and return response error. In that case set response type to text and manually check if it is empty. If it is - return original event with null body. Else parse.
import { Injectable } from '@angular/core';
import {
HttpEvent,
HttpInterceptor,
HttpHandler,
HttpRequest,
HttpResponse
} from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/do';
import 'rxjs/add/operator/map';
@Injectable()
export class EmptyResponseInterceptor implements HttpInterceptor {
/**
* In some cases API is returning empty response which cannot be parsed to JSON.
* If we have response type json angular will parse it automatically and return response error.
* In that case set response type to text and manually check if it is empty.
* If it is - return original event with null body. Else parse.
*/
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const newReq = req.clone({
responseType: 'text'
});
return next.handle(newReq).map((event: HttpEvent<any>) => {
if (event instanceof HttpResponse) {
let newEvent: HttpEvent<any>;
try {
newEvent = event.clone({ body: JSON.parse(event.body) });
} catch (err) {
// event.body === null
newEvent = event;
}
return newEvent;
}
});
}
}
@prameshbajra
Copy link

Thank you.
You are awesome. :) Have a great day.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment