Caching in Angular and MVC5

This article describes about the caching technics and its implementation in angularjs.

Data Caching is a performance technique to persist the data for a certain time interval. During this time, the data would fetch from the cache rather server. The persistence of data would be either in server or client. Here, in angular the persistence of data at client side that is on client browser.

Create a MVC project and add the angular core nugget package. Please refer my previous article on setting up the angular environment in MVC (SPA) project.

http://nullskull.com/a/10479043/spa-single-page-application-in-mvc-5-and-angularjs.aspx

Let’s add angular cache script files to MVC project and reference in Bundle.Config as below.

bundles.Add(
               new ScriptBundle("~/bundles/angularspa").Include(
                   "~/Scripts/jquery-{version}.js",
                   "~/Scripts/jquery-ui.js",
                   "~/Scripts/respond.js",
                   "~/Scripts/bootstrap.js",
                   "~/Scripts/angular.js",
                     "~/Scripts/angular-ui/ui-bootstrap-tpls.js",
                   "~/Scripts/angular-route.js",
                     "~/Scripts/ngProgress.js",
                     "~/Scripts/angular-cache.js",
                   "~/Scripts/angular/app.js",
                     "~/Scripts/angular/route.js",
                     "~/Scripts/angular/rootController.js",
                     "~/Scripts/angular/homeController.js"
                   ));

Add the angular-cache directive to angular module.

var app = angular.module('angularspa', ["ngRoute", "angular-cache"]);

Inject CacheFactory to the angular controller where you want to implement the caching.

app.controller('homeController', ["$scope", "$http", "$rootScope", "CacheFactory", function ($scope, $http, $rootScope, CacheFactory) {}]);

Now let’s create a cachefactory with options as below.

CacheFactory('profileCache', {
            maxAge: 15 * 60 * 1000, // Items added to this cache expire after 15 minutes
            deleteOnExpire: 'aggressive', // Items will be deleted from this cache when they expire
            storageMode: 'localStorage' // This cache will use `localStorage`.
        });

From above,   maxAge determines the time to persist the data.
deleteOnExpire determines the behaviour of the cache when data expires. Default none.
   none - Cache will do nothing when an item expires.
   passive - Cache will do nothing when an item expires. Expired items will remain in the cache until requested, at which point they are removed, and undefined is returned.
   aggressive - Cache will remove expired items as soon as they are discovered

storageMode determines the storage medium used by cache. Default memory.
   memory - Cache will hold data in memory. Data is cleared when the page is refreshed.
   localStorage - Cache will hold data in localStorage if available. Data is not cleared when the page is refreshed.
   sessionStorage - Cache will hold data in sessionStorage if available. Data is not cleared when the page is refreshed.

Use the cache factory in angular function as below.

var getUsers = function () {
        webUrl = 'http://localhost:50858/api/test/GetUsersFilterByName?query=A';
        var q = $q.defer();

        // get the cache factory
        var profileCache = CacheFactory.get('profileCache');

        // check and retive the data from cache
        if (profileCache.get('usersList')) {
            q.resolve(profileCache.get('usersList'));
        }
         else {

            $http.post(webUrl).then(function (response) {

                 //put the response data in cache and will be retrived during the cache life time on subsequent requests
                 profileCache.put('usersList', response.data);
                q.resolve(response.data);
            },
             function (error) {
                 q.reject(null);
             });
        }

         return q.promise;
    };

As we store the data in cache with key value pairs, first check for the data existence using key name. If exists, pull out from cache else initiate the service call and put the response in cache object.

Refer the angular cache documentation from angular site.
https://docs.angularjs.org/api/ng/service/$cacheFactory
https://jmdobry.github.io/angular-cache/

Download the working sample from below location. Make sure to add the missing nugget packages as they were removed because of size constraint.
http://nullskull.com/FileUpload/-407123783_angular-caching.zip       

By Siva Jagan Dhulipalla   Popularity  (2503 Views)