How to sync data with angular-data

3.2k Views Asked by At

I have a angular project with a angular-data to work with my Restful API.

my situation is as following:

in my service I return a defineresource in my controller I use service.defineresource.findAll().then

it all works fine but here is my question. when new data is added to the server how do I update the cache or add the new data to my cache.

Please advice

code: //in service.js

    .factory('Service', function(DS) {
     DS.defineresource({
        name: 'items'
        endpoint:'api/v2/users'
      });
     });

//in controller.js

    .controller('MainCtrl', function($scope, Service) {
      Service.findAll().then(function (data) {
        $scope.items = data
      });

   });

my code is above fetches all the data when I load it first time, but after the initial loading it only loads from the cache. My question is there a way to sync and fetch new data without destroying the cache.

2

There are 2 best solutions below

3
Wayne Ellery On BEST ANSWER

To force the refresh of the data from the backend you need to set bypassCache: true in the options. If you don't pass this then angular-data will load from cache. This is documented in the api documentation.

To refresh the data every 15 minutes use $timeout with 900000 milliseconds. To have a button to refresh use a scope function that will be called from a ng-click on a button.

.controller('MainCtrl', function($scope, $timeout, Service) {
    $scope.refreshData = function () {
        Service.findAll({}, { bypassCache: true }).then(function (data) {
            $scope.items = data;
        });
    }

    $scope.refreshData();

    $timeout($scope.refreshData, 900000);
});
<button ng-click="refreshData()">Refresh</button>
1
Tanuj Sanwal On

If you are using only Angular Routes, Use :

$route.reload()

it will reload / refresh your page . so the data will be sync . you can use it in ng-click or check in your controller when new data is entered use it

  $route.reload()

if you are using UI-Router you can do the same but instead of $route.reload() use this :

$state.go($state.current, {}, {reload: true});