我必须通过Interceptor对请求返回的主体应用解密,但解密方法是异步的并返回一个promise。
以下是该课程的摘录:
intercept(req: HttpRequest, next: HttpHandler): Observable> {
return next.handle(req).pipe(map((event: HttpEvent<any>) => {
if (event instanceof HttpResponse) {
let _body;
this.cryptMethod.decrypt(event.body).this(res => _body = res); // Método assíncrono
return event.clone({ body: JSON.parse(_body) });
}
return event;
}));
}`
事实证明“this.cryptMethod.decrypt()”是异步的,因此在填充_body之前会返回返回值。
这有什么解决方案吗?
你可以从mergeMap
和map
链中回复诺言。而不是使用.then
你也可以使用async
:
.pipe(mergeMap(async (event: HttpEvent<any>) => {
if (event instanceof HttpResponse) {
const _body = await this.cryptMethod.decrypt(event.body);
return event.clone({ body: JSON.parse(_body) });
}
});
你也可以这样做:
.pipe(
mergeMap(async (event: HttpEvent<any>) => {
if (event instanceof HttpResponse) {
return this.cryptMethod.decrypt(event.body);
}
}),
map(_body => {
if (_body) {
return event.clone({ body: JSON.parse(_body) });
}
})
);
...但它更冗长,需要两次有条件的检查。