Hi I am developing a web app which makes frequent get calls to a remote API. The response from the calls will always be the same so to speed up the performance of the site, I want to save the response in a JSON file locally so that the get requests are only called whenever the json file is empty.
Asked
Active
Viewed 2,754 times
-3
-
You can not store the data in a file, store in memory. In a variable. – Ashish Ranjan May 13 '19 at 02:44
-
Possible duplicate of [How to save JSON data locally (on the machine)?](https://stackoverflow.com/questions/28464449/how-to-save-json-data-locally-on-the-machine) – wentjun May 13 '19 at 02:47
2 Answers
1
You can not save JSON data to local file and load data because of security reason.
You can use localStorage
or sessionStorage
to save JSON object.
@Injectable()
export class YourService{
constructor(private http: HttpClient){
}
getData(){
var cached = JSON.parse(localStorage.setItem('yourkey'));
if(cached == null || cached == undefined){
this.http.get('yoururl').subscribe(data=>{
localStorage.setItem('yourkey', JSON.stringify(data);
return data;
});
}else{
return cached;
}
}
}

Hien Nguyen
- 24,551
- 7
- 52
- 62
-
The problem with this approach is that if there are multiple places that access the same cache value before the first load you fire off multiple http requests for the same key before the initial request is fulfilled. – Adrian Brand May 13 '19 at 04:23
-
this is fit with OP requirement, of course we have another solutions to cache – Hien Nguyen May 13 '19 at 04:25
1
I have written a library called ngx-rxcache which is exactly for this sort of thing.
https://github.com/adriandavidbrand/ngx-rxcache
I have written an article on it here https://medium.com/@adrianbrand/angular-state-management-with-rxcache-468a865fc3fb
@Injectable()
export class DataService{
get data$(): Observable<DataType> {
return this.dataCache.value$;
}
private dataCache = this.cache.get<DataType>({
id: 'some unique identifer',
construct: () => this.http.get<DataType>('/dataUrl'),
autoload: true
});
constructor(private http: HttpClient, private cache: RxCacheService) {}
}
and in a component use the data$ observable
data$ = this.dataService.data$;
and in the template use the async pipe.
{{ data$ | async }}

Adrian Brand
- 20,384
- 4
- 39
- 60