I need to cache server response in my service. I checked this question caching results with angular2 http service, here I have found 2 ways of doing that 1) Observable.share() - but as it said in the answer "he share() operator works just on the first request, when all the subscriptions are served and you create another one, then it will not work, it will make another Request" 2) use ReplaySubject works nice until using resolvers (it's creating new requests). Here is my plunker https://plnkr.co/edit/TiODzGyQtXepojf4oPgw you can check network tab, both ways creating new requests when you navigate from component A to component B. Any idea how to solve this problem?
my service
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import * as Rx from 'rxjs';
import { Http } from '@angular/http';
import { ReplaySubject } from 'rxjs/ReplaySubject';
@Injectable()
export class ContactsService {
goals: ReplaySubject<Array<any>> = new ReplaySubject(1);
constructor(private http: Http) {}
get() {
if (!this.goals.observers.length) {
return this.http
.get('https://jsonplaceholder.typicode.com/posts/1');
}
return this.goals;
}
get2() {
return this.http
.get('https://jsonplaceholder.typicode.com/posts/1').share();
}
}
Update
for subjects you can use the following method (suggested by ehrencrona)
cache: ReplaySubject<Array<any>>
get() {
if (!this.cache) {
this.cache = new ReplaySubject(1)
this.http.get(url).subscribe(this.cache)
}
return this.cache
}
for observable you can use this method I found out
observable: Observable<any>;
get() {
if (!this.observable) {
this.observable = this.http.get(url).publishReplay(1).refCount();
}
return this.observable;
}
Notice that .publishReplay(1).refCount() is not the same as .share() - with .share() it't creating new requests