繁体   English   中英

Angular-承诺的拦截器HTTP返回值

[英]Angular - Interceptor HTTP return value from promise

我必须通过拦截器在请求返回的主体上应用解密,但是解密的方法是异步的,并且返回诺言。

这是班上的节选:

 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之前已达到返回值。

有什么解决办法吗?

您可以从mergeMap和链map返回诺言。 除了使用.then之外.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) });
    }
  })
);

...但是比较冗长,需要两个条件检查。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM