我使用拦截器来缓存和返回缓存的数据,作为角4.3 HttpClient特性的一部分。下面是从拦截器调用的实用程序服务,用于存储和返回HTTP响应。
@Injectable()
export class LocalStorageCacheService implements HttpCache {
get(req: HttpRequest<any>): HttpResponse<any> {
return <HttpResponse<any>>JSON.parse(localStorage.getItem(btoa(req.url)))
};
put(req: HttpRequest<any>, resp: HttpResponse<any>): void {
localStorage.setItem(btoa(req.url), JSON.stringify(resp));
}
}
下面是我的拦截器,它检查缓存的条目,如果可用的话返回。
@Injectable()
export class CacheInterceptorService implements HttpInterceptor {
constructor(private localStorageCacheService: LocalStorageCacheService) {
}
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
if (req.method !== 'GET') {
return next.handle(req);
}
const cachedResponse = this.localStorageCacheService.get(req);
if (cachedResponse) {
**return Observable.of(cachedResponse);**
}
return next.handle(req).do(event => {
if (event instanceof HttpResponse) {
this.localStorageCacheService.put(req, event);
}
});
}
}
我遇到的问题是,http调用没有击中调用组件的订阅部分。即语句返回Observable.of(cachedResponse);似乎没有正确返回。
有什么想法吗?
更新#1
我发现了问题,它显然是从对象到HttpResponse类型的转换由于某些原因而没有发生,所以为了证明这一点,当我使用普通对象手动构造对象时,它开始工作了。但很明显,手工铸造是一件肮脏的事情,需要弄清楚为什么铸造不起作用。
if (cachedResponse) {
let httpResponse = new HttpResponse({
status : cachedResponse.status,
body : cachedResponse.body,
headers : cachedResponse.headers,
statusText : cachedResponse.statusText,
url : cachedResponse.url
});
return Observable.of(httpResponse)
};
发布于 2017-10-19 20:55:52
就像这样:
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return <HttpRequest<any>>req.catch((error) => {
return <HttpHandler>next.catch((err) => {
if (req.method !== 'GET') {
return next.handle(req);
}
const cachedResponse = this.localStorageCacheService.get(req);
if (cachedResponse) {
return Observable.throw(cachedResponse);
}
return next.handle(req).do(event => {
if (event instanceof HttpResponse) {
this.localStorageCacheService.put(req, event);
}
});
})
})
}
https://stackoverflow.com/questions/46842368
复制相似问题