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

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

    I guess you got two questions there removing repeated logic and best way to cache results.

    First - Removing duplicate code: Looks like townList.getTownList is the common method, the other two methods is an extension of this method. So,

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

    Second - caching values Now the call is being http made only in townList.getTownList, the logic to cache can be easily implemented here. But this depends on whether the data will be onetime fetch or can be refreshed. One time fetch: just enable the cache in the http call $http({method: 'GET', url: '/api/country/cities', cache:true});

    Refresh based on request: I would pass an refresh variable to inform whether data has to be refreshed or not. So if the refresh is true or the townList is empty the data will be fetched.

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

提交回复
热议问题