By using Http, we call a method that does a network call and returns an http observable:
getCustomer() {
return
I found a way to store the http get result into sessionStorage and use it for the session, so that it will never call the server again.
I used it to call github API to avoid usage limit.
@Injectable()
export class HttpCache {
constructor(private http: Http) {}
get(url: string): Observable {
let cached: any;
if (cached === sessionStorage.getItem(url)) {
return Observable.of(JSON.parse(cached));
} else {
return this.http.get(url)
.map(resp => {
sessionStorage.setItem(url, resp.text());
return resp.json();
});
}
}
}
FYI, sessionStorage limit is 5M(or 4.75M). So, it should not be used like this for large set of data.
------ edit -------------
If you want to have refreshed data with F5, which usesmemory data instead of sessionStorage;
@Injectable()
export class HttpCache {
cached: any = {}; // this will store data
constructor(private http: Http) {}
get(url: string): Observable {
if (this.cached[url]) {
return Observable.of(this.cached[url]));
} else {
return this.http.get(url)
.map(resp => {
this.cached[url] = resp.text();
return resp.json();
});
}
}
}