AngularJs节省资源/缓存 [英] AngularJs Resource saving/caching

查看:252
本文介绍了AngularJs节省资源/缓存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是AngularJs保存或以多个指令,它需要的资源结果得到它没有在服务器一再请求相同的资源缓存临时地方资源的结果的最佳方式?

What is the best way in AngularJs to save or cache temporary somewhere the resource result in order multiple directive which need the resource result to get it without requesting again and again the same resource in the server?

想象一下,有5指令,所有他们需要的资源的结果。

Imagine having 5 directives which all of them need the result of resource

http://foo.com/accounts

这将返回帐户的JSON(REST API GET方法)。

This returns a json of accounts (REST API GET method).

什么是该资源的缓存结果的最佳做法或将其保存到一个变量,然后每一个指令从这个变量中的数据,并避免击中REST API超过一次每1分钟(让缓存在1分钟内到期)

What is the best practice to cache result of this resource or save it to a variable and then each directive get the data from this variable and avoid hitting the rest API more than once every 1 minute (so cache expires in 1 minute)

非常感谢。

推荐答案

有几种方法可以做到这一点,但一个简单的自包含的方法是这样的:

There are a few ways to accomplish this but one simple self contained way would be something like this:

app.factory('myFactory', function($http) {
  var THRESHOLD = 60000; // 60 seconds
  var request = null;
  var timestamp;

  var service = {
    getResource: function() {
      var now = new Date().getTime();

      // only make a request if we haven't made one yet
      // or if its been longer than 60 seconds since the last request
      if(request === null || timestamp && now - timestamp > THRESHOLD) {
        timestamp = now;
        request = $http.get('http://some.service.com/resource');
      }

      // we're always returning a promise, once its resolved any service that
      // calls getResource won't have to wait for the request unless its been
      // over 60 seconds since the last one.
      return request;
    }
  }

  return service;
});

在这里基本的演示(略作修改,以模拟HTTP请求): http://plnkr.co /编辑/ QncVlV p =棉短绒

这篇关于AngularJs节省资源/缓存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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