我应该在angularjs app中加载基本数据。我初步创建工厂我想将数据加载到服务中,这样每当我需要数据时,我都会使用我的服务,而不是回到服务器。
提示::我的问题是我将ng-controller应用于不同的div,因此创建了很多实例,我不希望从每个实例的服务器加载数据。
app.factory('feedbackFactory', function ($http) {
//factory code
});
app.factory('feedbackService', function ($http) {
//service code
});
app.controller('feedbackController', function ($scope, feedbackService,feedbackFactory $filter) {
// Constructor for this controller
init();
function init() {
feedbackFactory.get(1234, 1, 20).then(function(data)
{
$scope.feedbackItems=data;
// here load data into service
});
}
});
答案 0 :(得分:0)
如果您的服务器支持缓存$http
,则默认使用E-Tags,并且实际上只从服务器获取数据一次(假设它没有更新并且电子标签更改)。这会导致它命中服务器,但会得到304
响应。
如果您想强制您的应用程序只与服务器通信一旦您需要设置某种变量,并检查它是否应该点击服务器......
app.factory('feedbackFactory', function ($http) {
var checkServer = true;
var results = [];
function getStuff(x, y, z) {
if (checkServer) {
checkServer = false; // we don't want to check again! Maybe have a refresh button that sets this back to true?
// do http call...
$http.get("path").then(function(response) {
// Here is the magic... use angular.copy to keep your results object the same but update its values!
angular.copy(response, results);
});
}
return results; // this will be updated by our inital call to the server!
});
});
这可能不是所有有效的代码,因为我只是打字了我的头脑,但它应该让你足够接近。大的绑定到results
对象并使用angular.copy(httpResponseData, results)
来填充数据,如果要在promise中绑定到调用本身而不是直接绑定,则可能需要返回$q.when(results)
绑定到feedbackFactory.results
;
app.factory('feedbackFactory', function ($http, $q) {
var checkServer = true;
var results = [];
function getStuff(x, y, z) {
if (checkServer) {
checkServer = false; // we don't want to check again! Maybe have a refresh button that sets this back to true?
// do http call...
return $http.get("path").then(function(response) {
// Here is the magic... use angular.copy to keep your results object the same but update its values!
angular.copy(response, results);
return results; // If you want to bind to the promise instead of .results directly
});
}
return $q.when(results); // If you want to bind to the promise instead of .results directly
});
});
答案 1 :(得分:0)
您可以使用$ http缓存,这样您的数据将不会在第一次从服务器获取。请参阅this answer以了解如何在$ http中使用缓存。