Created
August 2, 2018 07:16
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thank you.
You are awesome. :) Have a great day.