使用Angular 4.3.1和HttpClient,我需要通过异步服务将请求和响应修改为httpClient的HttpInterceptor。
修改请求的示例:
export class UseAsyncServiceInterceptor implements HttpInterceptor {
constructor( private asyncService: AsyncService) { }
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
// input request of applyLogic, output is async elaboration on request
this.asyncService.applyLogic(req).subscribe((modifiedReq) => {
const newReq = req.clone(modifiedReq);
return next.handle(newReq);
});
/* HERE, I have to return the Observable with next.handle but obviously
** I have a problem because I have to return
** newReq and here is not available. */
}
}
虽然响应的问题不同,但我需要再次应用逻辑来更新响应。在这种情况下,Angular指南建议像这样做:
response = applyLogic(response);
return next.handle(req).do(event => {
if (event instanceof HttpResponse) {
// your async elaboration
}
}
但是,“do()操作符会在不影响流值的情况下向Observable添加副作用”。
解决方案:关于请求的解决方案由bsorrentino(在被接受的答案中)提供,关于响应的解决方案如下:
return next.handle(newReq).mergeMap((value: any) => {
return new Observable((observer) => {
if (value instanceof HttpResponse) {
// do async logic
this.asyncService.applyLogic(req).subscribe((modifiedRes) => {
const newRes = req.clone(modifiedRes);
observer.next(newRes);
});
}
});
});
如何通过异步服务将请求和响应修改到httpClient拦截器中?
解决方案:利用rxjs优势。
.toPromise()
已被弃用,请使用return await lastValueFrom(next.handle(req));
。 - Lucas Vellido