下面的InvoiceModel有一个getByCustomer()函数,列出给定客户的发票。
我只是想知道与使用$ cacheFactory相比,将数据缓存到常规javascript变量之间的区别是什么。
常规Javascipt变量:
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;
}
};
}
]);
答案 0 :(得分:0)
我不会以你所展示的方式使用$cacheFactory
。您可以按照$http或$resource在内部使用它的方式使用它。
相反,您可以配置$http
或$resource
对象来缓存特定查询的响应。然后,您只需正常使用$http
或$resource
。它为您处理缓存。
$resource
的示例:
.factory('Invoice', ['$resource',
function($resource) {
return $resource('http://foo.bar/products', {}, {
query: { cache: true }
});
}
])
上面会覆盖资源的查询方法,以使用默认的$cacheFactory
启用缓存。您的代码第一次调用查询方法时,响应将被缓存。对查询方法的任何后续调用都将使用缓存的响应。
$http
的示例:
$http.get('/the-url', { cache: true }).then(...)
// or by passing in your own cache factory
var cache = $cacheFactory('myCacheFactory');
$http.get('/the-url', { cache: cache }).then(...);
清除缓存
当您需要清除缓存时,您会获得$cacheFactory
并调用它的remove()函数来清除相关网址的缓存:
// default cache factory
var defaultCache = $cacheFactory('$http');
defaultCache.remove('/some/url');
// custom cache factory
var cache = $cacheFactory('myCacheFactory');
cache.remove('/custom-cache-url');