嘿,在第一个$http请求中,我将结果保存在缓存中,我在控制器中使用了两个功能,在服务中调用相同的函数,其中调用第一个函数$Http$Http它将结果保存在缓存中,但对于第二个函数,当我尝试测试它时,Wehter缓存是否为空,它不应该为空,因为我已经将结果保存在缓存中,但它给出了我
未定义的错误
任何人都可以说出我的代码出了什么问题
这是控制器
vm.getTopHotels = function(){
var hotelsLimit = 10;
var top_hotels =
dataService.getHotels()
.then(
function(hotels){
console.log(hotels);
sortHotels = commonMethods.sortHotels(hotels.data.data,'Rating','SORT_DESC');
hotelDetailsCheck = checkDetailsIfExists(sortHotels);
//Get only top 10 hotels for home page
top_hotels = hotelDetailsCheck.slice(0,10);
vm.topHotels = top_hotels;
},
function(err){
console.log(err);
});
};
vm.getTopHotels();
vm.getRHotels = function(){
dataService.getHotels()
.then(function(hotels){
console.log('hotels recieced 2 ');
},
function(err){
console.log(err);
});
}
vm.getRHotels();
**dataService 是这里调用$http方法的 Facotry** 对于 vm.getTopHotels 我将结果保存在缓存中,因此在调用$Http时 getRHotels,我认为如果缓存不为空,它应该从缓存中检索数据,如果不是,那么它调用$Http请求,但对于这个函数,它也调用了$http为什么?因为我已经将结果保存在缓存中 谁能告诉我出了什么问题?
这是调用$http方法并保存在缓存中的数据服务代码
(function(){
angular
.module('app')
.factory('dataService',DataFactory);
DataFactory.$inject = ['$http','$q','$cacheFactory']
function DataFactory($http,$q,$cacheFactory){
var cache = $cacheFactory('localCache');
var service = {
getHotels:getHotels
};
return service;
function getHotels(){
var def = $q.defer();
var hotelsData = cache.get('hotelsData');
console.log(hotelsData);
if(!hotelsData){
$http.get('/hotels/getHotelsData')
.then(
function successCallback(data){
cache.put('hotelsData',data.data);
// service.hotels = data.data;
def.resolve(data);
},
function errorCallback(data){
def.reject('Failed to retrieve hotels');
});
return def.promise;
}else{
console.log('cached');
}
}
}
})();
实际上,您可以通过将 cache:true 添加到配置对象来指定缓存结果$http。
function getHotels() {
return $http.get('/hotels/getHotelsData', {cache:true});
}
您可以在此处阅读有关$http配置的更多信息:https://docs.angularjs.org/api/ng/service/$http
另外要澄清的是,$q.defer 是一个帮助程序,它允许您将非承诺 API 回调包装为承诺。 $http返回一个承诺。您可以返回 $http.get 的响应并对其执行 .then。
如果需要在返回数据之前对其进行操作,则仍然不需要将其包装在 $q.defer(( 中
function getHotels() {
return $http.get('/hotels/getHotelsData', {cache:true})
.then(function(response){
response.data[0].hotelName = 'changedName';
return response;
})
}
getHotels
函数有一个争用条件:在数据从服务器返回之前对该函数的第二次调用将允许第二个 HTTP GET 请求。
由于$http服务会立即返回承诺,因此最好缓存该承诺。
var hotelsPromise = null;
function getHotels(){
if (hotelsPromise) return hotelsPromise;
//ELSE
hotelsPromise = $http.get('/hotels/getHotelsData')
.then(function successCallback(response){
return response.data;
},
function errorCallback(response){
throw 'Failed to retrieve hotels';
});
return hotelsPromise;
}
这将避免错误的多个 HTTP GET 请求。