Angular2 the easiest way to cache HTTP responses

I have a page that makes HTTP requests in the same place, just with different parameters, depending on what the user wants. So my code looks something like this:

this.http.post( //I am open to POST methods or GET methods as I have security in the back to prevent malicious writes. 'http://192.168.1.45:3000/mylocation', 'p1=' + param1 + '&p2=' + param2, {headers: headers} ) 

In JQuery, for example, you have embedded a cache attribute in the framework, which is cached automatically and very easily implemented:

 $.ajax({ cache: true, //other options... }); 

Does Angular2 have something like this? I would like to cache these dynamic responses while the user is in the application. Therefore, if the user requests the same URL with the same parameters, he simply retrieves it from the cache, and if the parameters have never been used before, he will make a network call.

I could not find anything in the Angular2 docs in the query parameters:

https://angular.io/docs/js/latest/api/http/RequestOptions-class.html

+5
source share
1 answer

Download the data, and if caching data is available, return it, otherwise, execute an HTTP request. If you want to reuse different requests (parameters), you can configure them to store links in an array.

 getData() { if(this.data) { // if `data` is available just return it as `Observable` return Observable.of(this.data); else if(this.observable) { // if `this.observable` is set then the request is in progress // return the `Observable` for the ongoing request return this.observable; } else { // create the request, store the `Observable` for subsequent subscribers this.observable = this.http.get('/someUrl') .map(res => res.json()) .do(val => { this.data = val; // when the cached data is available we don't need the `Observable` reference anymore this.observable = null; }) // make it shared so more than one subscriber can get the result .share(); return this.observable; } } 
+10
source

Source: https://habr.com/ru/post/1246019/


All Articles