Comments (12)
Actually, ngResource uses $http "below", so you do get all the functionality from $http. If you want to cache something, you can just use the $cacheFactory set the URL and it'll be cached in $http, and therefore in $resource as well.
Same thing happens with default headers as you can see in the FAQ on how to add them.
from restangular.
Have you tried this?
from restangular.
An example would be helpful. Thanks Rob
from restangular.
Hey,
Take a look at this issue: #25
You'll have the example in the tests from AngularJS commit :).
Bests,
Gonto
from restangular.
Ok. Makes sense. Thanks for the reference.
from restangular.
No problem :). Glad to help!
from restangular.
As implementation on Angular's side wasn't really cool about caching (Tried out today), I've implemented it on Restangular.
In order to cache, you can do this:
https://github.com/mgonto/restangular#can-i-cache-requests
from restangular.
@mgonto @roboncode anyone else tried this with localstorage (/a localstorage wrapper around restangular in general?)
Thanks!
from restangular.
@mgonto I need more fine grained caching - for e.g how would I cache a getList call?
Something like:
myService = Restangular.service('people');
myService.getList('featured', {}, {cache: $resourceCache })
EDIT:
Doing this, which is not super succinct but works:
service = Restangular.all('people/featured')
service.withHttpConfig({cache: $resourceCache})
service.getList()
@mikermcneil BTW $resourceCache
in my example is an instance of angular-cache which can use localStorage (http://angular-data.pseudobry.com/documentation/guide/angular-cache)
from restangular.
Continuing this old thread, is there any way to cache a single getList request issued on a Restangular service? Example:
myService = Restangular.service('people');
// single record is ok
myService.one(12).withHttpConfig({cache: true}).then();
// how to do it with get list?
myService.withHttpConfig({cache: true}) // no such method .withHttpConfig()
myService.all().withHttpConfig({cache: true}) // no such method .all()
The method above to use Restangular.all('people').withHttpConfig({cache: true}).getList()
is a possible workaround in some cases, but not when the service originates from a locally configured Restangular.withConfig().service()
. The configuration will be lost when issuing the query from the unconfigured Restangular object.
Maybe add .withHttpConfig
or .all
to the service?
from restangular.
If found a way that works.
I declare a singleton (service) for keeping a global cache object
angular
.module('app.services')
.service('APICache', APICache);
function APICache($cacheFactory, $window) {
return $cacheFactory('http');
}
Then I use this singleton my Restangular derived factory
angular
.module('app.services')
.factory('API', API);
function API(Restangular, APICache) {
var cache = APICache;
var cacheTime = (new Date()).getTime();
var cacheExpiration = 1000 * 60 * 5; // 5 min
return Restangular.withConfig(function(RestangularConfigurer) {
RestangularConfigurer
.setDefaultHttpFields({cache:cache})
.setResponseInterceptor(function(response, operation) {
var currentTime = (new Date()).getTime();
var cacheExpired = (currentTime - cacheTime) > cacheExpiration;
if (cacheExpired || operation === 'put' || operation === 'post' || operation === 'delete') {
cache.removeAll();
cacheTime = (new Date()).getTime();
}
return response;
})
});
}
Then I can do all kind of request that will be cached and invalidated after 5min or when a modification request occurs.
When I want to clear the cache "permanently" (for the next requests), I have to inject APICache
where I use it and call APICache.removeAll();
.
Note that this is not perfect ..yet. We could remove only specific routes and the 5min delay is not reset. I think that APICache
could be a wrapper instead of an extension of $cacheFactory('http')
..and could include all timing data, etc...
Another approach could be make API a singleton that includes a Restangular service instance and a $cacheFactory instance. Then put method to control the cache or to use the api... only ideas
from restangular.
Here my final version with a wrapper around the cache factory instance
(function() {
'use strict';
angular
.module('app.services')
.factory('API', API);
function API(Restangular, APICache, $window) {
var headers = {
'Content-Type': 'application/json',
'Accept': 'application/x.api.v1+json'
};
return Restangular.withConfig(function(RestangularConfigurer) {
RestangularConfigurer
.setBaseUrl('/api')
.setDefaultHeaders(headers)
.setDefaultHttpFields({cache:APICache.getCache()})
.setErrorInterceptor(function(response, operation) {
if (response.status === 422 || response.status === 401) {
if (response.data.errors) {
for (var error in response.data.errors) {
//ngToast.danger({className: 'danger', content: response.data.errors[error][0]});
return response.data.errors[error][0];
}
}
if (response.message) {
//ngToast.danger({className: 'danger', content: response.message});
return response.message;
}
}
if (response.status === 500) {
if (response.message) {
//ngToast.danger({className: 'danger', content: response.message});
return response.message;
}
}
})
.setResponseInterceptor(function(response, operation) {
if (APICache.isExpired() || operation === 'put' || operation === 'post' || operation === 'delete') {
APICache.reset();
}
return response;
})
.addFullRequestInterceptor(function (element, operation, what, url, headers) {
var token = $window.localStorage.satellizer_token;
if (token) {
headers.Authorization = 'Bearer ' + token;
}
});
});
}
angular
.module('app.services')
.service('APICache', APICache);
function APICache($cacheFactory, $window) {
var cache = $cacheFactory('http');
var cacheTimer = (new Date()).getTime();
var cacheExpiration = 1000 * 60 * 5; // 5 min
this.getCache = function () {
return cache;
};
this.isExpired = function() {
var currentTime = (new Date()).getTime();
var cacheExpired = (currentTime - cacheTimer) > cacheExpiration;
return cacheExpired;
};
this.reset = function() {
cacheTimer = (new Date()).getTime();
cache.removeAll(); // todo could be improved/fine-tuned by passing type or url?
};
}
})();
from restangular.
Related Issues (20)
- Error when injecting restangular with angular 1.6.4 HOT 2
- Nested Services or Nested Configuration
- $remove() id as query parameter HOT 1
- new web app using restangular - www.connecttal.com -
- Element.plain() behaves differently compared to Retangular.stripRestangular
- How to make sync call?
- How to set array of object as parameters using customGET ?
- Did restangular support handling text/html or text/csv response?
- Response for getList SHOULD be an array and not an object or something else HOT 1
- make etag a strong etag when used in if-None-Match HOT 1
- Cancel request - Angular 1.5 HOT 1
- getList() response Json object loss some data
- How do I append query parameter with restangular.oneUrl()? HOT 1
- Details of HTTP request sent by put method ?
- Group by count
- addFullRequestInterceptor has empty headers object
- TypeError: Converting circular structure to JSON while <restangular-object>.put() HOT 1
- Multiple remove on Restangular
- Deprecated?
- Support DELETE method with body
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from restangular.