In angular application I want to encrypt the request and send it to server, also decrypt the response when receiving.
I have created a HttpInterceptor for both this task.
I am able to encrypt the request and it is working fine, But while decrypting response I am not able to do this.
Note : Both encrypt and decrypt are async methods:
@Injectable()
export class MyHttpInterceptor implements HttpInterceptor {
constructor(
private router: Router,
) {}
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return from(this.encryptRequest(req)).pipe(
switchMap((data) => {
return next.handle(data);
}),
tap(
(event:any) => {
if (event instanceof HttpResponse) {
this.decryptResponse(event).then((res:any)=>{
return next.handle(res);
});
}else{
return event;
}
},
(error):any => {
//......
},
),
);
}
async encryptRequest(request: HttpRequest<any>) {
//..encryption logic
}
async decryptResponse(response: HttpResponse<any>) {
//...decryption logic
}
}
But The decrypted response is not reaching to actual API call.
The tap
operator allows you to use the notifications emitted in the observable to perform parallel actions outside the observable pipeline(side-effects). So using tap the notifications emitted in the observable are not transform.
To transform the notifications you need to use one of the map
operators. In this case since you also want to map the response to an async process, you can use again the switchMap
operator.
return from(this.encryptRequest(req)).pipe(
switchMap((data) => next.handle(data)),
switchMap((event) =>
event instanceof HttpResponse
? from(this.decryptResponse(event))
: of(event)
)
);
cheers