我正在嘗試爲http請求做一個緩存工廠,所以它不會使服務器爲同一請求做很多工作。但似乎我使用推遲的「吞下」數據的方式,我不知道爲什麼。Angularjs Factory延遲的數據消失
控制檯輸出如下:
數據獲取:
對象{狀態: 「OK」,數據:對象的errorMessage:空,異常:空}
成功
不確定
ImportFactory:
factory("importFactory", function ($http, $q, loggingService) {
return{
fetchedData: [],
cacheTransport: function (transportsId, data) {
this.fetchedData.push({"transportsId": transportsId, "data": data});
},
getImport: function (transportsId) {
var factory = this;
var deferred = $q.defer();
var preFetchedTransport = this.findTransport(transportsId);
if (preFetchedTransport === null) {
console.log('fetching from backend');
return $http.post("/import/create/" + transportsId).then(function (data) {
console.log('data fetched:');
console.log(data);
factory.cacheTransport(transportsId, data);
deferred.resolve(data);
});
}
preFetchedTransport = deferred.promise;
return preFetchedTransport;
},
findTransport: function (transportsId) {
for (var i = 0; i < this.fetchedData.length; i++) {
var transportObj = this.fetchedData[i];
if (transportObj.transportsId === transportsId) {
return transportObj.data;
}
}
return null;
}
};
});
控制器
.controller('ImportController', function ($scope, $routeParams, importFactory){
$scope.transportId = $routeParams.id;
importFactory.getImport($scope.transportId).then(function (successData) {
console.log('success');
console.log(successData);
}, function (errorData) {
console.log('error');
console.log(errorData);
});
爲什麼不直接使用$ http的內置緩存,如$ http.post(url,{cache:true}) – 2015-03-19 12:25:48
因爲我需要更新緩存。 – 2015-03-19 12:27:46