Call a Promise from an Angular HttpInterceptor

此生再无相见时 提交于 2021-02-16 20:06:20

问题


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> {

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(

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.


回答1:


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



回答2:


Import the from operator in the component.

import { from } from 'rxjs';

Then call your encrypt() method, and in the response return the next.handle() object. Like this.

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

I'll let the link if you need it later. https://www.learnrxjs.io/



来源:https://stackoverflow.com/questions/53909136/call-a-promise-from-an-angular-httpinterceptor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!