拦截器类型“Observable”不可分配给类型 'Observable>'
我在处理缓存查询的响应时遇到问题。
为了提高应用程序的性能,我研究发现使用 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;
}
}
}
我怎样才能在拦截器中解决这个问题,以便我可以获得存储的响应?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在您的 TransferStateInterceptor 中,
虽然我相信您需要从“@angular/common/http”导入 HttpResponse 。
HttpEvent
的联合类型In your
TransferStateInterceptor
,While I believe you need to import
HttpResponse
from '@angular/common/http'.Union types for
HttpEvent