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?
问题:
回答1:
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)
}
});
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)
};
});
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
};
回答2:
You can use the cache
option in the config
argument to the various $http
methods:
$http.get('/someUrl', {
cache: true
});
回答3:
The most obvious way is simply to have a JavaScript integer variable that counts how many requests have been made to the server, and when a defined maximum limit is reached, to stop making requests to the server.
Without knowing more about why you want to do it, it is difficult to be more specific.