在我的 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' 变为'Support Request')。似乎正在发生的事情是在服务中“清理”数据后,CacheInterceptor 将响应添加到缓存中。因此,当再次发出相同的请求并从缓存中接收到时,服务正在尝试清理已被清理的数据。如何确保 HTTP 响应在被服务修改之前已被拦截并添加到缓存中?
1 回答
蝴蝶刀刀
TA贡献1801条经验 获得超8个赞
你如何通过将pipe(map(this.cleanData, this))操作移动到 Observable 完成并返回你的CaseResponse. 很可能,这意味着HttpInterceptor已首先应用。
即在你调用的地方getCases你可以尝试这样的事情:
service.getCases(options).subscribe(resolvedData => {
// assuming cleanData(data: CaseResponse) signature
const cleanedData = this.cleanData(resolvedData);
// .. do something with cleanedData
});
此外,从设计的角度来看,您不会想要getCases做的不仅仅是它应该做的事情 - 它是一种服务方法,它执行 HTTP 请求并以它们发送给您的格式返回案例。理想情况下,数据的重新格式化可以在该服务功能的消费者处完成 - 因为它很可能是需要对其进行清理/重塑的消费者。
添加回答
举报
0/150
提交
取消
