In the documentation about the new HttpClientModule
included in the new version of Angular 4.3, the mechanism to intercept requests is explained very well. There is also mention of the response interceptor mechanism however I cannot find anything about it.
Does anyone have an idea about how to intercept a response in order to modify the body message before it is sent to the service?
Thanks.
Since Angular 6 release, RxJs 6.0 changed its interface, so you cannot use operators the same way (like .map()
, .tap()
...).
Because of that, most of the above solutions are outdated.
This is how you correctly modify content of an Observable using RxJs 6.0+ (with pipe
):
import {HttpEvent, HttpHandler, HttpInterceptor, HttpRequest, HttpResponse} from '@angular/common/http';
import {Injectable} from '@angular/core';
import {Observable} from 'rxjs';
import {map} from 'rxjs/operators';
@Injectable()
export class ResponseInterceptor implements HttpInterceptor {
intercept(req: HttpRequest, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(req).pipe(map((event: HttpEvent<any>) => {
if (event instanceof HttpResponse) {
event = event.clone({body: this.modifyBody(event.body)});
}
return event;
}));
}
private modifyBody(body: any) {
/*
* write your logic to modify the body
* */
}
}