以official Angular docs中的HttpInterceptor缓存示例为例,它演示了使用startWith
将多值可观察流用于缓存的响应。
示例代码:
import {Injectable} from '@angular/core';
import {HttpEvent, HttpHandler, HttpInterceptor, HttpRequest, HttpResponse} from '@angular/common/http';
import {Observable} from 'rxjs';
import {tap, startWith} from 'rxjs/operators';
@Injectable()
export class CacheInterceptor implements HttpInterceptor {
intercept(req: HttpRequest<any>, next: HttpHandler) {
if (req.method !== 'GET') {
return next.handle(req);
}
const cachedResponse = cache.get(req);
const results$ = sendRequest(req, next);
return cachedResponse ? results$.pipe(startWith(cachedResponse)) : results$;
}
}
function sendRequest(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(req).pipe(
tap(event => {
if (event instanceof HttpResponse) {
cache.put(req, event);
}
})
);
}
export class HttpCache {
cache = new Map();
get(req: HttpRequest<any>): HttpResponse<any> | undefined {
const url = req.urlWithParams;
const cached = this.cache.get(url);
if (!cached) {
return undefined;
}
return cached.response;
}
put(req: HttpRequest<any>, response: HttpResponse<any>): void {
const url = req.urlWithParams;
const entry = {url, response, lastRead: Date.now()};
this.cache.set(url, entry);
}
}
const cache: HttpCache = new HttpCache();
该代码无效。它总是等待第二个可观察值,并且永远不会发出startWith
中包含的第一个值。有什么作用?