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

后端 未结 4 986
春和景丽
春和景丽 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:49

    There is nothing special that you can do and receive some considerable benefit. You would definitely need to cache your GET response and refactor a bit to avoid code duplication and improve readability:

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

    As for using $cacheFactory - seems like an overhead for such a simple scenario, just use built-in cache option.

提交回复
热议问题