Angular - 拦截器 HTTP return 来自 promise 的值

Angular - Interceptor HTTP return value from promise

我必须通过拦截器对请求的 return 主体进行解密,但是解密方法是异步的,return 是一个承诺。

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

原来"this.cryptMethod.decrypt ()"是异步的,所以在填充_body之前到达了return。

有什么解决办法吗?

您可以 return 来自 mergeMap 的承诺并将 map 链接到它。除了使用 .then,您还可以使用 async

.pipe(mergeMap(async (event: HttpEvent<any>) => {
  if (event instanceof HttpResponse) {
    const _body = await this.cryptMethod.decrypt(event.body);
    return event.clone({ body: JSON.parse(_body) });
  }
});

你也可以这样做:

.pipe(
  mergeMap(async (event: HttpEvent<any>) => {
    if (event instanceof HttpResponse) {
      return this.cryptMethod.decrypt(event.body);
    }
  }),
  map(_body => {
    if (_body) {
      return event.clone({ body: JSON.parse(_body) });
    }
  })
);

...但它更冗长并且需要两个条件检查。