By using Http, we call a method that does a network call and returns an http observable:
getCustomer() {
return
You can build simple class Cacheable<> that helps managing data retrieved from http server with multiple subscribers:
declare type GetDataHandler = () => Observable;
export class Cacheable {
protected data: T;
protected subjectData: Subject;
protected observableData: Observable;
public getHandler: GetDataHandler;
constructor() {
this.subjectData = new ReplaySubject(1);
this.observableData = this.subjectData.asObservable();
}
public getData(): Observable {
if (!this.getHandler) {
throw new Error("getHandler is not defined");
}
if (!this.data) {
this.getHandler().map((r: T) => {
this.data = r;
return r;
}).subscribe(
result => this.subjectData.next(result),
err => this.subjectData.error(err)
);
}
return this.observableData;
}
public resetCache(): void {
this.data = null;
}
public refresh(): void {
this.resetCache();
this.getData();
}
}
Usage
Declare Cacheable<> object (presumably as part of the service):
list: Cacheable = new Cacheable();
and handler:
this.list.getHandler = () => {
// get data from server
return this.http.get(url)
.map((r: Response) => r.json() as string[]);
}
Call from a component:
//gets data from server
List.getData().subscribe(…)
You can have several components subscribed to it.
More details and code example are here: http://devinstance.net/articles/20171021/rxjs-cacheable