How can I use my JSON without triggering a new API request everytime I want to use my data?

♀尐吖头ヾ 提交于 2019-12-18 09:45:18

问题


I'm wanting to to have my app limit its requests to the server without saving the data. Is there a way I can do this without making a request to the server every time my http request is invoked? What are some of the different methods this can be done and best practices/trade offs for each?


回答1:


That would depend on you needs. One approach would be to store the results in a request in a factory and retrieve those.

app.factory('DataService', function($http) {
  var values;
  var requestValues = function() {
    $http.get("/api/getValues").then(
        function(results){
            values = results;
        });
  };
  var getValues = function() {
    return values;
  };
  return {
    requestValues : requestValues, // this will make a http request and store the result
    getValues: getValues // this will call the stored result (without making a http request)
  }
});

And then in you controller call the functions to make a request for the values and then get the values. There are two functions, requestValues() to make the http request and save the result and getValues() to get the stored values without making a http request. Once requestValues() has been called, you should be able to call getValues() from anywhere to get the values without making a new http request.

myApp.controller('MyController', function ($scope, DataService) {
  var init = function (){
    DataService.requestValues(); // this will make the http request and store the result
    $scope.items = DataService.getValues(); // this will get the result
  };

  var justGetValues = function(){
    $scope.items = DataService.getValues(); // this will get the result (without making a http request)
  };

});

Now you simply have to call DataService.getUpdates(); whenever you need the values. (You might want to wrap these in a promise. I have refrained from doing this due to simplicity)

Alternatively you could use the cache option as mentioned by @JLRishe. Angular's $http has a cache built in, so simply set cache to true in its options

$http.get(url, { cache: true})
  .success(){ 
   // on success 
 }.error(){ 
  // on error
};



回答2:


You can use the cache option in the config argument to the various $http methods:

$http.get('/someUrl', {
    cache: true
});



回答3:


The most obvious way is simply to have a JavaScript integer variable that counts how many requests have been made to the server, and when a defined maximum limit is reached, to stop making requests to the server.

Without knowing more about why you want to do it, it is difficult to be more specific.



来源:https://stackoverflow.com/questions/33968655/how-can-i-use-my-json-without-triggering-a-new-api-request-everytime-i-want-to-u

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!