I'm just implementing HttpInterceptor
, where i would like to base64
encode the request body and base64
decode the response body.
Here is the code that i have done. When i debug it, the decoded data (i.e) json is being set back into event.body
. but, it is not getting received in the services, that actually makes the http call
@Injectable()
export class Base64Interceptor implements HttpInterceptor {
constructor(private base64UtilService: Base64UtilService) {
}
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
let requestClone = request.clone(
{
body: this.base64UtilService.encode(JSON.stringify(request.body)),
responseType: 'text'
}
)
return next.handle(requestClone).pipe(tap(event => {
if (event instanceof HttpResponse) {
debugger;
let decodedData = this.base64UtilService.decode(event.body);
event = event.clone({
body: decodedData
});
return event;
}
},
(err: any) => {
if (err instanceof HttpErrorResponse) {
console.log(err);
}
}))
}
}
I'm just getting the same response that actually comes from the server, the decoding of the event.body
is not reflecting. Thanks for the time
This is how the http call is made
sendActivationRequest(url: string, request: MyRequest): Observable<MyResponse> {
return this.httpClient.post<MyResponse>(url, request)
.pipe(map((response: MyResponse) => {
return response;
}), catchError((error) => {
return throwError(error);
}));
}
I obtained a modified response body successfully by using map instead of tap:
return next.handle(requestClone).pipe(map(event => {...}));
It's because of the behaviour of map vs. tap:
From the tap documentation: "Perform a side effect for every emission on the source Observable, but return an Observable that is identical to the source."
From the map documentation: "Applies a given project function to each value emitted by the source Observable, and emits the resulting values as an Observable."