【问题标题】:Call a Promise from an Angular HttpInterceptor从 Angular HttpInterceptor 调用 Promise
【发布时间】:2019-05-23 08:43:21
【问题描述】:

我有一个角度 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(

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

【问题讨论】:

  • 你使用的是什么版本的 rxjs?
  • 6.3.3 版本是 package.json 中的内容
  • 它可能应该,但我对 rxjs 真的很陌生。即使将它作为 Observable 我仍然不确定如何将两者放在一起。
  • 发布encrypt函数

标签: angular typescript observable es6-promise


【解决方案1】:

使用from 将promise 转换为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)
                })
               );
    }

【讨论】:

    【解决方案2】:

    在组件中导入from 运算符。

    import { from } from 'rxjs';
    

    然后调用您的 encrypt() 方法,并在响应中返回 next.handle() 对象。像这样。

    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    
      from(encrypt(obj: any).then(
      (data) => {  
       /* do the modifications */
       const modified = req.clone({ ..... });
       ...
       /* return the object interceptor function so it can work */
        next.handle(modified) 
      })
    

    如果您稍后需要,我会提供链接。 https://www.learnrxjs.io/

    【讨论】:

    • 我必须在 next.handle 之前调用它,因为它需要更改 modified 变量。
    • 没有。 req 是一个 HttpRequest 所以调用 clone() 也会返回一个 HttpRequest.
    • 但是现在拦截方法实际上并没有返回next.handle 调用。这就是我卡住的地方。
    • 现在,from() 运算符将 Promise 转换为 observable。现在让我;)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-06-10
    • 2019-10-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多