【问题标题】:Angular - Interceptor HTTP return value from promiseAngular - 来自承诺的拦截器 HTTP 返回值
【发布时间】:2018-08-30 18:58:19
【问题描述】:

我必须通过 Interceptor 对请求返回的主体应用解密,但是解密的方法是异步的并返回一个 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被填充之前就到了return。

有什么解决办法吗?

【问题讨论】:

    标签: angular http interceptor


    【解决方案1】:

    您可以从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) });
        }
      })
    );
    

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

    【讨论】:

    • 谢谢!第一个解决方案奏效了!非常感谢!
    猜你喜欢
    • 2020-03-14
    • 2018-03-30
    • 2018-12-28
    • 1970-01-01
    • 2015-11-04
    • 1970-01-01
    • 1970-01-01
    • 2023-03-13
    • 2017-08-04
    相关资源
    最近更新 更多