我使用了一个promise并缓存了来自服务器的响应。但是,当我尝试清除缓存并再次向服务器发出get请求时,它会继续向我提供缓存的响应。我知道刷新任务中的任务被设置为null,并且再次调用服务器但响应没有改变。直到我重新加载页面,它才会给我一个新的回复。
factory list.js
app.factory('listService', function($http, $q, $cookies) {
//Create a class
function listService() {
var self = this;
self.task = null;
self.getTask = function() {
var deferred = $q.defer();
//If we already have the data, we can resolve the promise.
if(self.task !== null) {
console.log("cache");
deferred.resolve(self.task);
} else {
//Get the data from the server.
$http.get('http://dstm.herokuapp.com/api/tasks')
.success(function(data) {
self.task = data;
console.log(self.task);
console.log("server");
deferred.resolve(data);
})
.error(function(response) {
console.log(response);
deferred.reject(response);
});
}
//return the promise.
return deferred.promise;
};
self.refreshTask = function(){
self.task = null;
console.log(self.task);
}
}
return new listService();
});
app.controller('feedController', function($route, $scope, authFact, $location, $cookies, dataService, fileReader,listService) {
$scope.task = "";
$scope.newTask = function(){
listService.getTask()
.then(
/* success function */
function(data) {
$scope.task = data;
},
/* error function */
function(result) {
console.log("Failed to get the name, result is " + result);
});
// $cookies.put('task', response.data);
// $scope.task = $cookies.get("task");
};
$scope.newTask();
$scope.refreshTask = function(){
listService.refreshTask();
$scope.newTask();
};
html
<button ng-click="refreshTask()" id="newTask" type="button">New Task</button>
答案 0 :(得分:0)
您需要从$httpDefaultCache
中删除该项目,如下所示:
$scope.refreshTask = function(){
// update controller to inject $httpDefaultCache
$httpDefaultCache.removeAll();
listService.refreshTask();
$scope.newTask();
};
您还可以致电$httpDefaultCache.remove('http://someurl.com/a/b/c')
以删除其网址中的单个项目。
有关详细信息,请查看$cacheFactory
上的文档:http://docs.angularjs.org/api/ng。$ cacheFactory