Calling only once / caching the data from a $http get in an AngularJS service

后端 未结 4 993
春和景丽
春和景丽 2021-02-10 16:50

This may sound like a really simply/stupid question but I need to ask it as I haven\'t came across this scenario before... okay I have a service in my angularJS app. this servic

4条回答
  •  灰色年华
    2021-02-10 17:29

    It is just as you say; this code can (and should) be refactored in many ways. One example:

    Let us factor the HTTP stuff into a separate service, that will also take care of caching. (Another idea for this would be to have a service for the HTTP/remote calls and another - maybe a general use decorator - to handle caching. LEt us not go into so much detail for now.) And let us put the formatting code in another method:

    The remote call service:

    .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
        };
    })
    

    The formatter:

    .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
        };
    })
    

    Your townDataService, written in terms of the above:

    .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;
    })
    

提交回复
热议问题