How can I cache json data returned from $http call. I use the following style of $http call:
$http({
url: 'SomeWebMethodUrl',
method: "POST",
data: "{'query':'somevalue'}",
headers: { 'Content-Type': 'application/json' }
}).success(function (data, status, headers, config) {
//something in success
}).error(function (data, status, headers, config) {
//something in error
});
I looked at the following tutorial: https://coderwall.com/p/40axlq on caching server response from $http call. But it is explaining $http.get() style and will cache data and will not make second $http request if the absolute URL is same.
Can I use caching with my style of $http call when my 'data' property is same for same webmethod calls in future? I am using ASP.net ASMX webservice for my WebMethods.
The usage of POST request used to add new records in the data store, PUT and DELETE modify the status of data store. And it doesn't make sense to cash any of them.
Only GET retrieve data without modifying data store. And this makes sense to cash it's response.
The angular.js cache is designed for HTTP GET calls only. This is consistent with the intent of the HTTP protocol, as HTTP servers don't usually look beyond the URL, the HTTP Method, and Cache-Control headers to determine whether they can respond to a request with cached content. Accordingly, the authors of angular did not extend the caching functionality to other HTTP methods.
Another way to look at it is that the angular $cache service is really just a simple key value store, with the URL of the request acting as a key and the response to the HTTP GET request the value that is stored locally instead of on the server.
When you think of it that way it becomes clear why it's more difficult to cache the response to a POST request. The content returned by the POST request depends not only on the URL, but the POSTed content. To cache that result in a key value store you need a mechanism to create an unique key that identifies both the URL and the data being passed.
If you data is simple enough, my suggestion is to write your own cache that is checked before you use the angular $http service. Without knowing more about your data method I can't give you a complete example, but you could do something like this:
You would then substitute this wrapper service where you currently use the raw $http service.
The point is to implement your own cache that understands the 'url+data' as a key before actually calling the $http service.