我正在使用$cacheFactory在我的缓存中保存一些数据,一切都很好,直到今天我决定将我的cacheFactory分离为一个名为MyFactory.js的类。现在我得到了错误:
TypeError: tableCacheFactory is not a function
因为注射是一种简单的方法,有人知道我是否遗漏了什么吗?
main.js
angular.module('main-component',
['my-component',
'my-cache-factory'
]);
MyFactory.js
angular.module('my-cache-factory', [])
.factory('tableCacheFactory', [
'$cacheFactory', function ($cacheFactory) {
return $cacheFactory('my-cache');
}
]);
MyService.js
angular.module('my-component', [])
.factory('my-component-service',
['$rootScope',
'$http',
'$q',
'tableCacheFactory',
function ($rootScope, $http, $q, tableCacheFactory) {
function getMyData (prodNro) {
var deferred = $q.defer();
var promise = deferred.promise;
var dataCache = tableCacheFactory.get('tablecache');
if (!dataCache) {
dataCache = tableCacheFactory('tablecache'); // TypeError: tableCacheFactory is not a function
}
var summaryFromCache = dataCache.get('tablecache' + prodNro);
if (summaryFromCache) {
deferred.resolve(summaryFromCache);
} else {
$http({
method: ...
data : ...
url: ...
}).success( function (data, status, headers, config) {
var objectResult = {
"data": data,
"status": status,
"headers": headers,
"config": config
}
if (data.response) {
// Save to cache
dataCache.put('tablecache'+prodNro, objectResult);
}
deferred.resolve(objectResult);
}).error(function (data, status, headers, config) {
...
});
}
return promise;
}
您似乎对$cacheFactory
的工作方式有一些误解。
在var dataCache = tableCacheFactory.get('tablecache');
中,您使用它就像它是一个包含另一个Cache对象的初始化Cache对象一样。
另一方面,dataCache = tableCacheFactory('tablecache');
使用它就像$cacheFactory
本身一样。
他们两个都试图访问记录"tablecache",我认为这应该已经是tablecache本身了。
错误正是它所说的。根据文档,调用$cacheFactory('my-cache');
不会返回创建更多缓存的函数。它返回一个$cacheFactory.Cache
对象,该对象具有类似put(key, value)
和get(key)
的方法。请使用这些。
我会更改缓存的整个结构(注意,工厂的名称已经更改):
.factory('tableCache', [
'$cacheFactory', function ($cacheFactory) {
//Return what the name of the factory implies
return $cacheFactory('tablecache');
}
]);
然后使用它,而不需要做更多奇怪的"表缓存"命名
function getMyData (prodNro) {
...
var summaryFromCache = tableCache.get(prodNro);
...
tableCache.put(prodNro, objectResult);
}
tableCacheFactory
封装在my-cache-factory
模块内。因此,在使用my-component
模块之前,您需要先将该模块注入。因此,它应该是这样的:
angular.module('my-component', ['my-cache-factory'])
您在模块my缓存工厂中定义了缓存工厂,但从未将该模块注入主组件服务模块。改为执行angular.module('my-component', ['my-cache-factory'])
。