猿问

$http 结果未从缓存中检索?

嘿,在第一个 $http 请求中,我将结果保存在缓存中,我在控制器中使用了两个函数,在服务中调用相同的函数,其中在 $Http 的第一个函数中调用 $Http 它将结果保存在缓存中,但对于第二个函数,当我试图测试它是否缓存为空它不应该为空,因为我已经将结果保存在我的缓存中,但它给了我


未定义的错误


谁能告诉我我的代码出了什么问题


这是控制器


    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 是 Facotry,它为 vm.getTopHotels 调用 $http 方法 ** 我将结果保存在缓存中,因此在调用 $Http 时 getRHotels 我正在检查如果缓存不为空,它应该检索数据如果不是,则从缓存中调用 $Http 请求,但对于此函数,它也调用 $http 为什么?因为我已经将结果保存在缓存中 谁能告诉我出了什么问题?


这是调用 $http 方法并保存在缓存中的 dataService 代码


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

       

呼唤远方
浏览 169回答 2
2回答

哆啦的时光机

该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 请求。
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答