编程语言
首页 > 编程语言> > javascript – 只调用一次/缓存AngularJS服务中的$http get数据

javascript – 只调用一次/缓存AngularJS服务中的$http get数据

作者:互联网

这可能听起来像一个非常简单/愚蠢的问题,但我需要问它,因为我之前没有遇到过这种情况……好吧我在angularJS应用程序中有一项服务.此服务目前包含4个方法,所有方法都执行80%相同的功能/代码,我希望提高效率.这是我的服务看起来像(删除了大量代码):

    .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’.这远远没有效果!将此功能放入其自身功能的最佳方法是什么,所以我们只调用一次GET url但仍返回每个方法的承诺?我应该将$http({method:’GET’,url:’/ api / country / cities’})的结果设置为var并在必要时格式化数据之前将其注入/传递到每个方法中吗?我应该使用某种$cacheFactory吗?

对不起,如果这是一个愚蠢的问题,如果我没有解释好自己,我会重新解释这些问题.

提前致谢.

解决方法:

就像你说的那样;这段代码可以(并且应该)以多种方式进行重构.一个例子:

让我们将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;
})

标签:javascript,angularjs,angularjs-service
来源: https://codeday.me/bug/20190528/1173746.html