2017-02-26 151 views
0

我正在構建一個應用程序,用於從JSON文件中添加和刪除項目。 我遇到了以下問題:當我刪除一個項目時,它會反映在前端(該項目消失),但需要幾個硬頁面重新加載讓應用程序讀取我生成的新JSON文件PHP文件而不是緩存的文件。在AngularJS中處理緩存和更新的JSON文件

如果我只是重新加載一次,它只會讀取緩存中的JSON文件,這並不反映所做的更改。

有沒有什麼辦法可以直接在AngularJS中處理這個問題?

這裏是我的角碼:

$scope.remove = function(array, index){ 
    if($scope.totsselected){ 
     array.splice(index, 1); 
     $http.post("deleteall.php", { 
      data : array 
     }) 
     .then(function(data, status, headers, config) { 
     $http.get('data/all.json') 
      .then(function (response) { 
       $scope.productesgenerals = response.data; 
       console.log($scope.productesgenerals); 
      }).catch(function (error) { 
     }); 
     }); 
    } 
)}; 

我的PHP代碼:

<?php 

$contentType = explode(';', $_SERVER['CONTENT_TYPE']); 

$rawBody = file_get_contents("php://input"); // Read body 
$data = json_decode($rawBody); // Then decode it 
$all = $data->data; 

$jsonData = json_encode($all); 
file_put_contents('data/all.json', $jsonData); 
?> 

回答

1

這聽起來像你有$ HTTP緩存打開。嘗試禁用它爲此請求

$http.get('data/all.json', {cache: false}) 

https://docs.angularjs.org/api/ng/service/ $ HTTP緩存#

如果不工作(它仍緩存),那麼它聽起來像服務器端緩存。你可以通過發送一個唯一的查詢字符串來破解它。

$http.get('data/all.json?_=' + Date.now(), {cache: false}) 

這將使每個請求一個唯一的請求,並應防止服務器端緩存。

需要注意的是,由於您忽略了緩存,因此您將失去緩存的所有性能優勢。