author thumb

Software Developer

Caching a JSONP Request

Caching a JSONP request — Medium

Today I needed to cache a JSONP request, in angularJS , so the first thing I tried to do is use the own $http cache functionality. Result ? Does not work!

I’ll try to explain why.
When you make JSONP requests you first need to specify a callback , right? In AngularJS you need this:

If you look at the Browser Developer Tools , will notice that request is modified to something like this :

Why ?

Simply to enable asynchronous requests, and make the AngularJS remember who he must deliver each callback . So it is necessary to create different urls for each request , making it impossible to cache the conventional way !

Then, tried to use his own $CacheFactory the AngularJS to perform this function, and is working perfectly so far.

The first thing you need to do is inject the $cacheFactory in your Service, along with $q(optional) and $http

.factory('MyService', function($http,  $q, $cacheFactory) {

Now you need to define your caches name

var cacheEngine = $cacheFactory("Categories");

And last, but not less important, check if there is any stored cache

return {  
allCached: function () {  
var cache = cacheEngine.get('ListCategories');  
var deferred = $q.defer();
// Get from cache  
} else {  
$http.jsonp(server+"categories?callback=JSON_CALLBACK",{cache: true}).  
success(function(data) {  
// Store to cache  
cacheEngine.put('ListCategories', data);  
return deferred.promise;  

You can use this service in your controller easly

.then(function (data) {  
$scope.myCategories = data;  

After that we need to know if the cache is actually being done right? Open the developer tools and note that the first request is made normally, but if you go to another page and then return to this listing categories, you will see that the request has not even been taken, because it is already cached!

I hope that in futures version this can be easly done, in AngularJS

author thumb

Hugo Dias

Desenvolvedor Back-end & Front-end, Desenvolvimento Android e IOS, HTML5, CSS3 e JavaScript