Search code examples
angulartypescriptobservablees6-promise

Call a Promise from an Angular 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> {

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.


Solution

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