我有一個$資源,用於獲取一個或所有註冊,創建新的或更新現有的註冊,刪除註冊......作品。這裏的資源的代碼:
.factory('Registrations', function ($resource) {
return $resource('api/registrations/:assetType/:registrationId',
{assetType: '@assetType', registrationId: '@assetRegistrationId'},
{query: {
method: 'GET',
cache: true,
isArray: true
}}
);
})
正如你可以看到,緩存到位,並能正常工作:後續請求不會傳播到服務器。除創建或刪除註冊後外,緩存不會更新。
對於移除我已經想出了這個解決方法。它看起來很糟糕,但它很有用。這裏也有一些奇怪的事,但注意:
Registrations.delete({assetType: $scope.assetType, registrationId: registration.assetRegistrationId}, function() {
//doesn't seem to work -> dirty hack
//$cacheFactory.get('$http').remove('api/registrations/' + $scope.assetType + '/' + registration.registrationId);
var cached = $cacheFactory.get('$http').get('api/registrations/' + $scope.assetType);
var cachedRegistrations = JSON.parse(cached[1]);
var registrationInCache = get(cachedRegistrations, registration.assetRegistrationId);
if (registrationInCache) {
cachedRegistrations.splice(cachedRegistrations.indexOf(registrationInCache), 1);
cached[1] = JSON.stringify(cachedRegistrations);
}
$scope.registrations = Registrations.query({assetType: $scope.assetType});
//...
令人驚訝的是,緩存不保留的JavaScript對象的列表,但只有1與代表所有項目的JSON的實際字符串項。我正在做的是對該字符串進行json化,刪除已刪除的項目並再次對該列表進行字符串化。
對於創作,我沒有那麼有創意,我只能刪除緩存中的一個條目(代表完整的集合)並重新載入服務器中的所有數據。以下是我如何使緩存無效。
$cacheFactory.get('$http').remove('api/registrations/' + $scope.assetType);
我可能錯過了一些明顯的東西。任何人有任何建議或澄清?謝謝!
因此,如果你不與服務器通信,爲什麼你需要使用'cache'? – NicolasMoise
它說我不在與服務器通信?我只是想在我添加/刪除一個項目後更新我的客戶端$緩存。其實我會認爲角的$資源會爲我做這個。 –
「但我正在更改客戶端上的這些數據 - 不需要往返於服務器。」也許我誤解了你的問題,但爲什麼你需要緩存?你不能只更新你的客戶端對象嗎? – NicolasMoise