Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS Caching a REST request

I'm new to angularJS and have a question about caching etc.

I have a wizard with two steps, I want to be able to click back and next and have the forms still filled out as the user had them.

In my page1Partial i have this:

<li ng-repeat="pick in picks | orderBy:orderProperty">
<b><span ng-bind="pick.name"/></b>
<input type="checkbox" ng-model="pick.checked" ng-click="updateBasket(pick)">
</li>

When i go to the next page, then click back the checkboxs are cleared, and its because my RESful call to a java service is called again. How can I cache this response?

From my controller, this hits my REST web service every time.

$scope.picks = Pick.query();

My service

angular.module('picksService', ['ngResource']).
    factory('Pick', function ($resource) {
        return $resource('rest/picks/:id', {}, {
            'save': {method: 'PUT'}
        });
    });
like image 861
catrapture Avatar asked Mar 14 '13 06:03

catrapture


People also ask

How to cache data in AngularJS?

To enable cache for an HTTP request you set the cache property on the $http configuration object to true. Angular will now cache the HTTP response object in the default $http cache object. That object can be retrieved by using the get method on the $cachefactory and passing it $http as the first parameter.

How to resolve cache issue in AngularJS?

There are several ways around this, you can: Configure the webserver to tell browsers not to cache the file. This is obviously inefficient as the user will have to download the same file time and time again. Append a query string parameter to the filename such as my-angular-code.

How to set http request header in AngularJS?

To add headers for an HTTP method other than POST or PUT, simply add a new object with the lowercased HTTP method name as the key, e.g. $httpProvider. defaults. headers. get = { 'My-Header' : 'value' } .


2 Answers

Since 1.1.2 (commit), all the $httpConfig options are directly exposed in $resource action objects:

return {
  Things: $resource('url/to/:thing', {}, {
    list : {
      method : 'GET',
      cache : true
    }
  })
 };
like image 79
Narretz Avatar answered Oct 04 '22 05:10

Narretz


if you replace $resource with $http then you can directly use below code

$http({
    method: 'PUT',
    url: 'url',
    cache:true
});
like image 38
Ajay Beniwal Avatar answered Oct 04 '22 07:10

Ajay Beniwal