我在处理缓存查询的响应时遇到问题。
为了提高应用程序的性能,我研究了使用TransferStateInterceptor是最佳解决方案。但不幸的是,我在返回缓存的响应时遇到了一个小问题。
在我的研究中,这个答案似乎是解决方案https://stackoverflow.com/a/53492870/8747207
我也想在这个视频中实现这个解决方案,但在返回缓存的响应时总是遇到同样的问题
问题似乎是返回响应的类型,但我还没有找到任何关于如何解决这个问题的有用信息。
错误特别出现在这一行中
return of(new HttpResponse<any>({ body: cachedResponse })); // here is the type fail
错误消息是:
Type 'Observable<HttpResponse>' is not assignable to type 'Observable<HttpEvent<any>>'.
Type 'HttpResponse' is not assignable to type 'HttpEvent<any>'.
Type 'HttpResponse' is missing the following properties from type 'HttpResponse<any>': type, clone, status, statusText, and 2 more.
在我尝试实现的两个解决方案中,只要我必须返回HttpResponse,它就会失败。
这是我在拦截器中的代码示例。
import { Injectable } from '@angular/core';
import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor} from '@angular/common/http';
import { Observable, of } from 'rxjs';
import { TransferStateService } from '../internal/transfer-state.service';
import { HttpResponse } from 'aws-sdk';
import { tap } from 'rxjs/operators';
@Injectable()
export class TransferStateInterceptor implements HttpInterceptor {
constructor(private transferStateService: TransferStateService) {}
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
if (req.method !== 'GET') {
return next.handle(req);
}
const cachedResponse = this.transferStateService.getCache(req.url);
if (cachedResponse) {
return of(new HttpResponse<any>({ body: cachedResponse })); // here is the type fail
}
return next.handle(req).pipe(
tap(event => {
if (event instanceof HttpResponse) {
this.transferStateService.setCache(req.url, event.body);
}
})
);
}
}
这是我的TransferStateService
import { isPlatformBrowser } from '@angular/common';
import { Inject, Injectable, PLATFORM_ID } from '@angular/core';
import { makeStateKey, TransferState } from '@angular/platform-browser';
const transferStateCache: String[] = [];
@Injectable({
providedIn: 'root'
})
export class TransferStateService {
constructor(private transferState: TransferState, @Inject(PLATFORM_ID) private platformId) {}
setCache(key: string, data: any) {
if (!isPlatformBrowser(this.platformId)) {
transferStateCache[key] = makeStateKey<any>(key);
this.transferState.set(transferStateCache[key], data);
}
}
getCache(key: string): any {
if (isPlatformBrowser(this.platformId)) {
const cachedData: any = this.transferState['store'][key];
delete this.transferState['store'][key];
return cachedData;
}
}
}
我如何在拦截器中解决这个问题,以便获得存储的响应?
在您的TransferStateInterceptor
中,
import { HttpResponse } from 'aws-sdk';
虽然我认为您需要从"@angular/common/http"导入HttpResponse
。
HttpEvent
的并集类型
import { ..., HttpResponse } from '@angular/common/http';