Processing $http response in service

后端 未结 12 1668
半阙折子戏
半阙折子戏 2020-11-22 03:36

I recently posted a detailed description of the issue I am facing here at SO. As I couldn\'t send an actual $http request, I used timeout to simulate asynchrono

12条回答
  •  甜味超标
    2020-11-22 04:25

    As far as caching the response in service is concerned , here's another version that seems more straight forward than what I've seen so far:

    App.factory('dataStorage', function($http) {
         var dataStorage;//storage for cache
    
         return (function() {
             // if dataStorage exists returned cached version
            return dataStorage = dataStorage || $http({
          url: 'your.json',
          method: 'GET',
          cache: true
        }).then(function (response) {
    
                  console.log('if storage don\'t exist : ' + response);
    
                  return response;
                });
    
        })();
    
    });
    

    this service will return either the cached data or $http.get;

     dataStorage.then(function(data) {
         $scope.data = data;
     },function(e){
        console.log('err: ' + e);
     });
    

提交回复
热议问题