I'm attempting to leverage Angular 4.3+ HTTP_INTERCEPTORs to create a cache.
The idea that if the call's result has already been cached, it should push the cached result on the observable, and then continue with the http call.
This way, the user gets to see his data instantly if it's cached, so he can view it while the server is still retrieving the (potentially unchanged) data.
However, I don't know how to return an observable with an initial value that will get processed properly by the .subscribe.
For example:
someApi.get$(1).subscribe((result: any) => {
console.log("Got result " + result);
});
...
// inside the interceptor
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
// whole bunch of logic
let cachedResult = somethingRetrievedFromMyCache;
// How do I "return" cachedResult?
// Things I've tried:
// .startWith(cachedResult)
// Observable.of(cachedResult).concat(next.handle(request))
return next.handle(request);
}
Expected scenario:
Got result [cachedResult]
Got result [newResult]
Thanks
Observable.of(cachedResult).concat(next.handle(request))
? This looks correct to me. – martincachedResult
wasn't empty? – martin