使用$ cacheFactory与常规javascript变量AngularJS缓存数据

时间:2015-03-21 03:15:27

标签: angularjs

下面的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;
            }
        };
    }
]);

1 个答案:

答案 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');