问题
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