在我的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响应之前确保HTTP响应已被拦截并添加到缓存中?
通过将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请求并以发送给您的格式返回案例。数据的重新格式化可以理想地在该服务功能的使用者处完成-因为很有可能需要清洗/重塑的使用者。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句