-2

My requirement is I have to store large amount of data using angular for pagination. This data will come from server side. How can we do it using angular?. Thanks in advance.

Charan Ghate
  • 1,384
  • 15
  • 32
abhi_88
  • 62
  • 5

1 Answers1

0

If you want to cache data you can do it in a number of ways. Two of approaches are here:-

  1. Use $http inbuild cache that's simple (details in link above).

    $http.get(url, { cache: true}).success(...);

  2. Use $cacheFactory (details in link above)

  3. Simply cache it inside your service:-

Service:-

    var todoApp = angular.module("todoApp",[]);

    todoApp.factory('dbService', ['$q','$http',function ($q , $http) {  
    var service ={};
    service.localCache = {hasdata:false,data:{},lastLoaded:new Date()};

        service.getUrl = function (urlToGet,burstCache) {
            var svc=this;

            var deferred = $q.defer();
            if ((!burstCache)&&(svc.localCache)&&(svc.localCache.hasdata)) {
                    console.log('resolve from local cache');
                    return(svc.localCache.data);
            }else{
            var responsePromise = $http.get(urlToGet);

            responsePromise.success(function (data, status, headers, config) { 
                svc.localCache={}; 
                svc.localCache.hasdata=true; 
                svc.localCache.data=data; 
                svc.localCache.lastLoaded= new Date(); 
                deferred.resolve(data); 
                console.log('resolve from ajax') });

            responsePromise.error(function (data, status, headers, config) { 
                deferred.reject({ error: "Ajax Failed", errorInfo: data }); svc.localCache={}; });
            }
            return (deferred.promise);
        }

        return service;
        }]);

Controller:-

 todoApp.controller("ToDoCtrl",['$scope','$timeout','dbService',function($scope, $timeout, dbService)
    {
        $scope.todo={};
      //Fetches the data from server. 'true' means burstCache
      $timeout(function(){
       dbService.getUrl('/api/userdata',true).then(function(resp){
        $scope.todo=resp;
       });},1);

    //ReLoads the data from cache
    $scope.reLoad=function(){
        $scope.todo={};
        $timeout(function() {$scope.todo=dbService.getUrl('/api/userdata');},1000);

    };
    }]);
Community
  • 1
  • 1
amitthk
  • 1,115
  • 1
  • 11
  • 19