Caching data using $cacheFactory vs regular javascript variable AngularJS -
the invoicemodel below has getbycustomer() function lists invoices given customer.
i'm wondering what's difference between caching data regular javascript variable compared using $cachefactory.
regular javascipt variable:
angular.module('app', ['ngresource'])  .factory('invoice', ['$resource',     function($resource) {         return $resource('http://foo.bar/invoices');     } ]) .factory('invoicemodel', ['invoice',     function(invoice) {         var customer_invoices = [];          return {             getbycustomer: function(customer_id) {                 if (customer_invoices[customer_id] == undefined) {                     customer_invoices[customer_id] = invoice.get({customer_id: customer_id});                 }                  return customer_invoices[customer_id];             }         };     } ]); $cachefactory
angular.module('app', ['ngresource'])  .factory('invoice', ['$resource',     function($resource) {         return $resource('http://foo.bar/products');     } ]) .factory('invoicemodel', ['invoice', '$cachefactory',     function(invoice, $cachefactory) {         var customerinvoicescache = $cachefactory('customerinvoicescache');          return {             getbycustomer: function(customer_id) {                 var invoices = customerinvoicescache.get(customer_id);                  if (!invoices) {                     customerinvoicescache.put(invoice.get({customer_id: customer_id}));                 }                  return invoices;             }         };     } ]); 
i wouldn't use $cachefactory in fashion have shown. you're kind of using way $http or $resource use internally.
instead, can configure $http or $resource object cache responses specific queries. merely use $http or $resource normal. handles caching you. 
example $resource:
.factory('invoice', ['$resource',     function($resource) {         return $resource('http://foo.bar/products', {}, {             query: { cache: true }         });     } ]) the above overrides query method of resource enable caching default $cachefactory. first time code calls query method response cached. subsequent calls query method use cached response.
example $http:
$http.get('/the-url', { cache: true }).then(...) // or passing in own cache factory var cache = $cachefactory('mycachefactory'); $http.get('/the-url', { cache: cache }).then(...); clearing cache:
when need clear cache, $cachefactory , call it's remove() function clear cache associated url:
// default cache factory var defaultcache = $cachefactory('$http'); defaultcache.remove('/some/url'); // custom cache factory var cache = $cachefactory('mycachefactory'); cache.remove('/custom-cache-url'); 
Comments
Post a Comment