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

查看:22
本文介绍了每次我想使用我的数据时,如何使用我的 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(); 即可.(您可能想将这些包装在 promise 中.为了简单起见,我没有这样做)

或者,您可以使用@JLRishe 提到的缓存选项.Angular 的 $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天全站免登陆