2014-03-27 44 views
0

我有一個$資源,用於獲取一個或所有註冊,創建新的或更新現有的註冊,刪除註冊......作品。這裏的資源的代碼:

.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); 

我可能錯過了一些明顯的東西。任何人有任何建議或澄清?謝謝!

+0

因此,如果你不與服務器通信,爲什麼你需要使用'cache'? – NicolasMoise

+0

它說我不在與服務器通信?我只是想在我添加/刪除一個項目後更新我的客戶端$緩存。其實我會認爲角的$資源會爲我做這個。 –

+0

「但我正在更改客戶端上的這些數據 - 不需要往返於服務器。」也許我誤解了你的問題,但爲什麼你需要緩存?你不能只更新你的客戶端對象嗎? – NicolasMoise

回答

1

我相信這種緩存應該在服務器端完成,而不是在前端(AngularJS)完成。我不是100%確定Angular的cache=true是如何工作的,但我相信它只是緩存結果,所以額外的請求會得到緩存的結果。 Angular無法分辨服務器上的數據何時發生變化。

+0

但我在客戶端上更改此數據 - 不必往返於服務器。 –

+0

對,爲什麼你需要緩存?如果它已經在客戶端上(比如Angular緩存),那麼它應該非常快,或者至少與從緩存加載一樣快。 – NicolasMoise

+0

我的觀點是在這兩種情況下,你正在加載已經在客戶端中的東西,所以不需要使用緩存。 – NicolasMoise

相關問題