-3

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.

2

2 Answers 2

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 }}
Sign up to request clarification or add additional context in comments.

Comments

0

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

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.
this is fit with OP requirement, of course we have another solutions to cache

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.