Следуя примеру кэша HttpInterceptor из официальных документов Angular , он демонстрирует использование наблюдаемого потока с несколькими значениями для кэшированных ответов с помощью 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();
Код не работает.Он всегда ждет 2-го наблюдаемого и никогда не выдает первое значение, содержащееся в startWith
.Что дает?