首页 > 解决方案 > 从 Angular HttpInterceptor 调用 Promise

问题描述

我有一个角度HttpInterceptor,我需要调用一个定义如下的加密方法:

private async encrypt(obj: any): Promise<string> {

我不确定如何在 HttpInterceptor 中处理这个问题:

intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    const modified = req.clone({ 
       body: this.encrypt(req.body)
    });

    return next.handle(modified).pipe(

我不确定如何将这两者联系在一起,以便我可以encryptintercept函数中正确调用该方法。

标签: angulartypescriptobservablees6-promise

解决方案


用于将promisefrom转换为 observable 并使用switchMap操作符进行您需要的修改并返回处理程序。

  intercept(request: HttpRequest<any>, next: HttpHandler) : Observable<HttpEvent<any>>{
        return from( this.encrypt(req.body))
              .pipe(
                switchMap(data=> { // do the changes here
                  const modified = req.clone({ 
                           body: data
                  });

                  return next.handle(modified)
                })
               );
    }

推荐阅读