簡體   English   中英

Angular HttpInterceptor分別對請求和響應進行加解密

[英]Angular HttpInterceptor to encrypt and decrypt request and response respectively

在 angular 應用程序中,我想加密請求並將其發送到服務器,同時在接收時解密響應。

我為這兩個任務創建了一個 HttpInterceptor。

我能夠加密請求並且工作正常,但是在解密響應時我無法做到這一點。

注意:加密和解密都是異步方法:

@Injectable()
export class MyHttpInterceptor implements HttpInterceptor {
  
    constructor(
        private router: Router,
    ) {}

    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return from(this.encryptRequest(req)).pipe(
        switchMap((data) => {
            return next.handle(data);
        }),
        tap(
            (event:any) => {
                if (event instanceof HttpResponse) {
                    this.decryptResponse(event).then((res:any)=>{
                      return next.handle(res);
                    });

                }else{
                    return event;
                }

            },
            (error):any => {
                  //......
            },
        ),
       
    );
    }

async encryptRequest(request: HttpRequest<any>) {
//..encryption logic
}

async decryptResponse(response: HttpResponse<any>) {
//...decryption logic
 }
    }

但是解密的響應沒有到達實際的 API 調用。

tap操作符允許你使用 observable 中發出的通知在 observable 管道之外執行並行操作(副作用)。 因此,使用點擊在可觀察中發出的通知不會轉換。

要轉換通知,您需要使用map運算符之一。 在這種情況下,由於您還希望 map 響應異步進程,您可以再次使用switchMap運算符。

return from(this.encryptRequest(req)).pipe(
  switchMap((data) => next.handle(data)),
  switchMap((event) =>
    event instanceof HttpResponse
      ? from(this.decryptResponse(event))
      : of(event)
  )
);

干杯

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM