Angular - HTTP Interceptor returns the value of a promisse

Asked

Viewed 95 times

0

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

Follow a section of 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 turns out that the this.cryptMethod.decrypt() is asynchronous, so Return is reached before _body is filled.

Is there any solution to this?

1 answer

0


Try using an async Function, so you can use await inside the function to wait for the return of Promise.

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;
}));
}`

  • Thanks man, it worked here! Thanks!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.