一只斗牛犬
2022-01-13 16:21:03
在我的 Angular 8 應(yīng)用程序中,我有一個基本的緩存攔截器: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 檢索數(shù)據(jù)的服務(wù): public getCases(options: ModuleArguments): Observable<CaseResponse> { return this.http .get<CaseResponse>(this.URL_BASE, { params: options as HttpParams }) .pipe(map(this.cleanData, this)); }'cleanData' 方法只是循環(huán)接收到的數(shù)據(jù)并修改一些值以使它們更人性化(例如將'support_request' 變?yōu)?#39;Support Request')。似乎正在發(fā)生的事情是在服務(wù)中“清理”數(shù)據(jù)后,CacheInterceptor 將響應(yīng)添加到緩存中。因此,當(dāng)再次發(fā)出相同的請求并從緩存中接收到時,服務(wù)正在嘗試清理已被清理的數(shù)據(jù)。如何確保 HTTP 響應(yīng)在被服務(wù)修改之前已被攔截并添加到緩存中?
1 回答

蝴蝶刀刀
TA貢獻1801條經(jīng)驗 獲得超8個贊
你如何通過將pipe(map(this.cleanData, this))操作移動到 Observable 完成并返回你的CaseResponse. 很可能,這意味著HttpInterceptor已首先應(yīng)用。
即在你調(diào)用的地方getCases你可以嘗試這樣的事情:
service.getCases(options).subscribe(resolvedData => {
// assuming cleanData(data: CaseResponse) signature
const cleanedData = this.cleanData(resolvedData);
// .. do something with cleanedData
});
此外,從設(shè)計的角度來看,您不會想要getCases做的不僅僅是它應(yīng)該做的事情 - 它是一種服務(wù)方法,它執(zhí)行 HTTP 請求并以它們發(fā)送給您的格式返回案例。理想情況下,數(shù)據(jù)的重新格式化可以在該服務(wù)功能的消費者處完成 - 因為它很可能是需要對其進行清理/重塑的消費者。
添加回答
舉報
0/150
提交
取消