如何确保可观察量的运算符在 HTTP 拦截器之后发生?



在我的 Angular 8 应用程序中,我有一个基本的缓存拦截器:

export class CacheInterceptor implements HttpInterceptor {
constructor(private cache: CacheService) {}
public intercept(
req: HttpRequest<any>,
next: HttpHandler
): Observable<HttpEvent<any>> {
if (req.method !== 'GET') {
return next.handle(req);
}
const cachedResponse = this.cache.get(req);
if (cachedResponse) {
console.log(cachedResponse);
return of(cachedResponse);
}
return next.handle(req).pipe(
filter(event => event instanceof HttpResponse),
map((response: HttpResponse<any>) => {
this.cache.addToCache(req, response);
return response;
})
);
}
}

我还有一个从外部 API 检索数据的服务:

public getCases(options: ModuleArguments): Observable<CaseResponse> {
return this.http
.get<CaseResponse>(this.URL_BASE, {
params: options as HttpParams
})
.pipe(map(this.cleanData, this));
}
">

cleanData"方法只是循环访问接收到的数据并修改一些值以使它们对人类更友好(例如,将"support_request"转换为"支持请求"(。

似乎正在发生的事情是在服务中"清理"数据后,响应被 CacheInterceptor 添加到缓存中。因此,当再次发出相同的请求并从缓存中接收到时,服务将尝试清除已清理的数据。

如何确保 HTTP 响应在服务修改之前已被截获并添加到缓存中?

通过将pipe(map(this.cleanData, this))操作移动到可观察量完成并返回CaseResponse时,您如何解决这个问题。很可能,这将意味着首先应用了HttpInterceptor

即在你调用getCases的地方,你可以尝试这样的事情:

service.getCases(options).subscribe(resolvedData => {
// assuming cleanData(data: CaseResponse) signature
const cleanedData = this.cleanData(resolvedData);  
// .. do something with cleanedData 
});

此外,从设计的角度来看,您不希望getCases做超出其预期操作的操作 - 这是一种执行 HTTP 请求并以发送给您的格式返回案例的服务方法。理想情况下,数据的重新格式化可以在该服务功能的使用者处完成 - 因为很可能是需要清理/重塑它的消费者。

最新更新