Angular - HTTP interceptor return the value of a promise

0

I have to apply a descriptografia on the body of the return of a request via Interceptor , however the decryption method is asynchronous and returns a promisse .

Here's an excerpt from the class:

intercept(req: HttpRequest, next: HttpHandler): Observable> {

return next.handle(req).pipe(map((event: HttpEvent<any>) => {
  if (event instanceof HttpResponse) {
    let _body;

    this.cryptMethod.decrypt(event.body).this(res => _body = res); // Método assíncrono

    return event.clone({ body: JSON.parse(_body) });

  }
  return event;
}));
}'

It happens that this.cryptMethod.decrypt() is asynchronous, so the return is reached before the _body is filled in.

Is there a solution to this?

    
asked by anonymous 30.08.2018 / 19:22

1 answer

0

Try to use an async function, this way you can use await within the function to wait for the promise to return.

intercept(req: HttpRequest, next: HttpHandler): Observable> {

return next.handle(req).pipe(map(async (event: HttpEvent<any>) => {
  if (event instanceof HttpResponse) {
    let _body;

    await this.cryptMethod.decrypt(event.body).then(res => _body = res); // Método assíncrono

    return event.clone({ body: JSON.parse(_body) });

  }
  return event;
}));
}'
    
30.08.2018 / 21:39