如何在angularjs中cachinghttp get服务

我希望能够创build一个自定义服务,在ts数据对象为空的情况下获取http get请求,并在成功时填充数据对象。 下一次进行服务调用时,设备将不会调用http get,而是显示数据对象。

任何想法如何做到这一点?

Angular的$ http有一个内置的caching 。 根据文件:

cache – {boolean | Object} – 用$ cacheFactory创build的布尔值或对象 ,用于启用或禁用HTTP响应的caching。 请参阅$ httpcaching以获取更多信息 。

布尔值

所以你可以在其选项中将cache设置为true

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

或者,如果您更喜欢configurationtypes的呼叫:

 $http({ cache: true, url: url, method: 'GET'}).success(...); 

caching对象

您也可以使用caching工厂:

 var cache = $cacheFactory('myCache'); $http.get(url, { cache: cache }) 

你可以使用$ cacheFactory来实现它(特别是在使用$ resource的时候):

 var cache = $cacheFactory('myCache'); var data = cache.get(someKey); if (!data) { $http.get(url).success(function(result) { data = result; cache.put(someKey, data); }); } 

我认为现在有一个更简单的方法。 这为所有的$ http请求启用了基本的caching($ resourceinheritance):

  var app = angular.module('myApp',[]) .config(['$httpProvider', function ($httpProvider) { // enable http caching $httpProvider.defaults.cache = true; }]) 

在当前稳定版本(1.0.6)中执行此操作的更简单方法需要的代码less得多。

设置你的模块后,添加一个工厂:

 var app = angular.module('myApp', []); // Configure routes and controllers and views associated with them. app.config(function ($routeProvider) { // route setups }); app.factory('MyCache', function ($cacheFactory) { return $cacheFactory('myCache'); }); 

现在你可以把它传递给你的控制器:

 app.controller('MyController', function ($scope, $http, MyCache) { $http.get('fileInThisCase.json', { cache: MyCache }).success(function (data) { // stuff with results }); }); 

一个缺点是键名也是自动设置的,这可能会使得清除它们非常棘手。 希望他们会以某种方式添加键名。

如果你喜欢$ http的内置caching,但想要更多的控制,请查看库的angular-cache 。 您可以使用它来无缝地增加$ http cache的生存时间,定期清除以及将caching持久保存到localStorage的选项,以便跨会话可用。

FWIW,它还提供了工具和模式,使您的caching成为一种更dynamic的数据存储,您可以与POJO进行交互,而不仅仅是默认的JSONstring。 目前还无法评论该选项的实用性。

(然后,最重要的是,相关的库angular度数据是$资源和/或Restangular的替代品,并且依赖于angular度caching。)

由于AngularJS工厂是单身人士 ,您可以简单地存储http请求的结果,并在下次将服务注入到某个东西时检索它。

 angular.module('myApp', ['ngResource']).factory('myService', function($resource) { var cache = false; return { query: function() { if(!cache) { cache = $resource('http://example.com/api').query(); } return cache; } }; } ); 
 angularBlogServices.factory('BlogPost', ['$resource', function($resource) { return $resource("./Post/:id", {}, { get: {method: 'GET', cache: true, isArray: false}, save: {method: 'POST', cache: false, isArray: false}, update: {method: 'PUT', cache: false, isArray: false}, delete: {method: 'DELETE', cache: false, isArray: false} }); }]); 

设置caching为true。