从Angular HttpInterceptor调用Promise [英] Call a Promise from an Angular HttpInterceptor

查看:42
本文介绍了从Angular HttpInterceptor调用Promise的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I've got an angular HttpInterceptor and I need to call an encryption method that's defined like so:

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

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

I'm not sure how to handle this in the HttpInterceptor though:

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

    return next.handle(modified).pipe(

我不确定如何将两者结合在一起,以便可以从 intercept 函数内部正确调用 encrypt 方法.

I'm not sure how to tie the two of those together so that I can call the encrypt method properly from within the intercept function.

推荐答案

使用 from 将诺言转换为可观察的,并使用 switchMap 运算符进行您需要的修改,返回处理程序.

USe from to convert promise to observable and use the switchMap operator to do the modification u need and return the handler.

  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)
                })
               );
    }

这篇关于从Angular HttpInterceptor调用Promise的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆