从 Angular HttpInterceptor 调用 Promise

Gar*_*yle 2 observable typescript es6-promise angular

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

private async encrypt(obj: any): Promise<string> {
Run Code Online (Sandbox Code Playgroud)

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

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

    return next.handle(modified).pipe(
Run Code Online (Sandbox Code Playgroud)

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

Sac*_*aka 6

使用from许诺转化为可观察到的,并使用switchMap运营商做的修改u需要和返回的句柄。

  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)
                })
               );
    }
Run Code Online (Sandbox Code Playgroud)