我如何使用我的JSON,而不会触发一个新的API请求,每次我想用我的数据? [英] How can I use my JSON without triggering a new API request everytime I want to use my data?

查看:203
本文介绍了我如何使用我的JSON,而不会触发一个新的API请求,每次我想用我的数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想有我的应用程序限制了其对服务器的请求不保存数据。有没有一种方法,我可以做到这一点,而无需对我的每一个HTTP请求调用时服务器的请求?什么是一些不同的方法可以做到这一点,最好的做法/权衡每一个?

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?

推荐答案

这将取决于你的需要。一种方法是将存储在在工厂的请求的结果,并检索这些

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

然后在你控制器调用的函数,以便为值的请求,然后获取值。有两个函数, requestValues​​()来使HTTP请求,并保存结果和的GetValues​​()来获得存储的值而不进行http请求。一旦 requestValues​​()被调用,你应该能够调用的GetValues​​()从任何地方获得的值不制作一个新的HTTP请求。​​

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

});

现在您只需拨打 DataService.getUpdates(); 时,你需要的值。 (您可能希望从这样做,由于简单的承诺把它们包装。我禁止)




另外,您可以使用由@JLRishe提到缓存选项。角的$ HTTP内置了高速缓存,因此只需设置缓存为true,在其选项

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

这篇关于我如何使用我的JSON,而不会触发一个新的API请求,每次我想用我的数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆