In an angularjs app, I am attempting to use a custom service to hold the app's main data, "items". However, I would like to bootstrap the data into the service upon the initial page load, in order to avoid a separate ajax request to the server to get it. What would be cleanest way to go about doing this?
在angularjs应用程序中,我试图使用自定义服务来保存应用程序的主要数据“项目”。但是,我想在初始页面加载时将数据引导到服务中,以避免向服务器发出单独的ajax请求。这样做最干净的方法是什么?
Here is a snippet of my service for reference:
以下是我的服务片段供参考:
app.factory('items', function() {
var itemsService = {},
items = [];
itemsService.list = function() {
return items;
};
itemsService.add = function() {
/* ... */
};
return itemsService;
});
And on the backend I am using node.js + expressjs + jade, so I would be injecting the data into the page using:
在后端我使用node.js + expressjs + jade,所以我将使用以下方法将数据注入页面:
!{JSON.stringify(items)}
2 个解决方案
#1
3
Put your bootstrapped data from the server into a global JavaScript variable. Have your service assign items
to that global variable (or copy the data into items
).
将来自服务器的引导数据放入全局JavaScript变量中。让您的服务将项目分配给该全局变量(或将数据复制到项目中)。
#2
1
How about something like this:
这样的事情怎么样:
app.run(['items', function (items) {
items.load();
}])
This presumes your items
service has a load
function (or something like it) that does the actual Ajax work using either $http or $resource.
这假设您的项目服务具有加载功能(或类似的东西),使用$ http或$ resource执行实际的Ajax工作。
#1
3
Put your bootstrapped data from the server into a global JavaScript variable. Have your service assign items
to that global variable (or copy the data into items
).
将来自服务器的引导数据放入全局JavaScript变量中。让您的服务将项目分配给该全局变量(或将数据复制到项目中)。
#2
1
How about something like this:
这样的事情怎么样:
app.run(['items', function (items) {
items.load();
}])
This presumes your items
service has a load
function (or something like it) that does the actual Ajax work using either $http or $resource.
这假设您的项目服务具有加载功能(或类似的东西),使用$ http或$ resource执行实际的Ajax工作。