Calling only once / caching data from $ http in AngularJS service

This may sound like a really simple / stupid question, but I need to ask about it since I have not come across this script before ... well, I have a service in my angularJS application. this service currently contains 4 methods, each of which executes 80% of the same functionality / code, and I want to make it more efficient. This is what my service (with remote code) looks like:

    .factory('townDataService', function ($http) {

        var townList = {};

        townList.getTownList = function () {

            return $http({method: 'GET', url: '/api/country/cities'})
                .then(function (response) {

                    // HERE WE FORMAT THE response as desired... that creates a returnArray
                    var returnArray = [];
                    // loop through the countries
                    var JsonData = response.data;

                    for (key in JsonData['countries']) {
                         // formatting code...
                    }
                    // end of repeated CODE

                    return returnArray; // this is array, we don't do any formatting here

                });
        };


     townList.getCurrentTown = function (place) {

            return $http({method: 'GET', url: '/api/country/cities'})
                .then(function (response) {

                    // HERE WE FORMAT THE response as desired... that creates a returnArray
                    var returnArray = [];
                    // loop through the countries
                    var JsonData = response.data;

                    for (key in JsonData['countries']) {
                         // formatting code...
                    }
                    // end of repeated code

                    // now the format further / work with the returnArray...
                    for (var i = 0; i < returnArray.length; i++) {
                        // do stuff
                    }
                    return currentTown; // this is a string

                });
        };


        townList.getCurrentCountry = function (place) {

            return $http({method: 'GET', url: '/api/country/cities'})
                .then(function (response) {

                    // HERE WE FORMAT THE response as desired... that creates a returnArray
                    var returnArray = [];
                    // loop through the countries
                    var JsonData = response.data;

                    for (key in JsonData['countries']) {
                         // formatting code...
                    }
                    // end of repeated code

                    // now the format further / work with the returnArray...
                    for (var i = 0; i < returnArray.length; i++) {
                        // do stuff
                    }
                    return currentCountry; // this is a string

                });
        };

        return townList;

    }
)
;

$http 'GET' ( ), . ! , URL- GET, ? $http({method: 'GET', url: '/api/country/cities'}) var / , ? - $cacheFactory?

, , , .

.

+4
4

, ; ( ) . :

HTTP , . ( , HTTP/ , - , - . .) :

:

.service('townHttpService', function($http, $q) {
    var cache;

    function getCities() {
        var d = $q.defer();
        if( cache ) {
            d.resolve(cache);
        }
        else {
            $http({method: 'GET', url: '/api/country/cities'}).then(
                function success(response) {
                    cache = response.data;
                    d.resolve(cache);
                },
                function failure(reason) {
                    d.reject(reason);
                }
            });
        }
        return d.promise;
    }

    function clearCache() {
        cache = null;
    }

    return {
        getCities: getCities,
        clearCache: clearCache
    };
})

:

.service('townFormatter', function() {
    return function townFormatter(jsonData) {
        // HERE WE FORMAT THE response as desired... that creates a returnArray
        var returnArray = [], key;
        // loop through the countries
        for (key in jsonData['countries']) {
             // formatting code...
        }
        // end of repeated CODE
        return returnArray; // this is array, we don't do any formatting here
    };
})

townDataService, :

.factory('townDataService', function (townHttpService, townFormatter) {

    var townList = {};

    townList.getTownList = function () {
        return townHttpService.getCities().then(townFormatter);
    };

    townList.getCurrentTown = function (place) {
        return townHttpService.getCities().then(townFormatter).then(function(cityList) {
            var currentTown;
            for (var i = 0; i < cityList.length; i++) {
                // do stuff
            }
            return currentTown; // this is a string
        });
    };

    townList.getCurrentCountry = function (place) {
        return townHttpService.getCities().then(townFormatter).then(function(cityList) {
            var currentCountry;
            for (var i = 0; i < cityList.length; i++) {
                // do stuff
            }
            return currentCountry; // this is a string
        });

    return townList;
})
+3

, . GET , :

.factory('townDataService', function ($http) {
    var getCitiesAsync = function(){
        return $http({method: 'GET', url: '/api/country/cities', cache:true});
    };

    var townList = {};

    townList.getTownList = function () {
        return getCitiesAsync().then(prepareTownList);
    };

    var prepareTownList = function(response){
        //extract towns and do whatever you need
        return result;
    };

    ...

$cacheFactory - , , .

+1

, : .

- : , townList.getTownList - , - . ,

townList.getCurrentTown = function(place) {
  var towns = townList.getTownList();
  for (var i = 0; i < returnArray.length; i++) { //additional stuff
  }
  return currentTown;
};


townList.getCurrentCountry = function(place) {
  var towns = townList.getTownList();
  for (var i = 0; i < returnArray.length; i++) { //additional stuff
  }
  return currentCountry;
};

- http townList.getTownList, . , . : http- $http({method: 'GET', url: '/api/country/cities', cache:true});

: refresh, , . , , .

var srvc = this;
var townList;
townList.getTownList = function(refresh ) {
  if (refresh || !townList) {
    srvc.townList = $http({
      method: 'GET',
      url: '/api/country/cities'
    })
      .then(function(response) {
        var returnArray = [];
        var JsonData = response.data;
        for (var key in JsonData.countries) {}
        return returnArray; // this is array, we don't do any formatting here
      });
  }

  return townList;
};
+1

, , :

function getCities() {
        var d = $q.defer();
        if( cache ) {
            d.resolve(cache);
        }
        else {
            $http({method: 'GET', url: '/api/country/cities'}).then(
                function success(response) {
                    if (!cache) {
                        cache = response.data;
                    }
                    d.resolve(cache);
                },
                function failure(reason) {
                    d.reject(reason);
                }
            });
        }
        return d.promise;
    }

, (, ) - , , ​​ . , . , cache, :

function success(response) {
    if (!cache) {
        cache = response.data;

There is no need to create problems, but if you rely on the presence of identical objects (for example, when working with data binding), then it is very simple to make sure that data is extracted only once!

+1
source

Source: https://habr.com/ru/post/1543355/


All Articles