Search code examples
javascriptjsonangularjsngresource

AngularJS, save resource service json to localstorage and update conditionally


I need to update local-cached data by download large-size data from server only when new version detected, I am using ngResource,

goodServices.factory('Good', ['$resource',
  function($resource){
    return $resource('../WebService/list_goods.ashx?gid=:gid', {}, {
      query: {method:'GET', params:{q:'all'}, isArray:true}
    });
  }]);

How to request and save the responded data to LocalStorage every time, when new version (GET a version number) detected.


Solution

  • for communicating with local storage I want to suggest ngStorage you can inject it in your controller

    function yourBaseController(Good,$localStorage){
       var newVersion = Good.get(..your params), // it should return your new version
           currentVersion = $localStorage.version;
       if(newVersion !== currentVersion ){
          $localStorage.version = newVersion;
       }
    }
    

    Or if you don't have a base controller which is working at all time when your app bootstraps, you can move this logic in .run block