2

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.

Gargoyle
  • 9,590
  • 16
  • 80
  • 145

2 Answers2

6

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)
                })
               );
    }
Sachila Ranawaka
  • 39,756
  • 7
  • 56
  • 80
0

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/

Yoarthur
  • 909
  • 9
  • 20