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.
-
You can not store the data in a file, store in memory. In a variable.Ashish Ranjan– Ashish Ranjan2019-05-13 02:44:28 +00:00Commented May 13, 2019 at 2:44
-
Possible duplicate of How to save JSON data locally (on the machine)?wentjun– wentjun2019-05-13 02:47:50 +00:00Commented May 13, 2019 at 2:47
Add a comment
|
2 Answers
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 }}
Comments
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;
}
}
}
2 Comments
Adrian Brand
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.
Hien Nguyen
this is fit with OP requirement, of course we have another solutions to cache