我想在页面加载后尽快执行 Meteor 集合查询.我尝试的第一件事是这样的:
I want to perform a Meteor collection query as soon as possible after page-load. The first thing I tried was something like this:
Games = new Meteor.Collection("games"); if (Meteor.isClient) { Meteor.startup(function() { console.log(Games.findOne({})); }); }但这不起作用(它打印未定义").当从 JavaScript 控制台调用时,相同的查询会在几秒钟后生效.我认为在数据库准备好之前存在某种滞后.那么我怎么知道这个查询什么时候会成功呢?
This doesn't work, though (it prints "undefined"). The same query works a few seconds later when invoked from the JavaScript console. I assume there's some kind of lag before the database is ready. So how can I tell when this query will succeed?
OSX 10.8 和 Chrome 25 下的流星版本 0.5.7 (7b1bf062b9).
Meteor version 0.5.7 (7b1bf062b9) under OSX 10.8 and Chrome 25.
推荐答案您应该首先发布来自服务器的数据.
You should first publish the data from the server.
if(Meteor.isServer) { Meteor.publish('default_db_data', function(){ return Games.find({}); }); }在客户端,只有在从服务器加载数据后才执行集合查询.这可以通过在 subscribe 调用中使用反应式会话来完成.
On the client, perform the collection queries only after the data have been loaded from the server. This can be done by using a reactive session inside the subscribe calls.
if (Meteor.isClient) { Meteor.startup(function() { Session.set('data_loaded', false); }); Meteor.subscribe('default_db_data', function(){ //Set the reactive session as true to indicate that the data have been loaded Session.set('data_loaded', true); }); }现在,当您执行集合查询时,您可以检查数据是否已加载:
Now when you perform collection queries, you can check if the data is loaded or not as:
if(Session.get('data_loaded')){ Games.find({}); }注意:删除 autopublish 包,它默认将您的所有数据发布到客户端,这是不好的做法.
Note: Remove autopublish package, it publishes all your data by default to the client and is poor practice.
要删除它,请从根项目目录对每个项目执行 $meteor remove autopublish.
To remove it, execute $ meteor remove autopublish on every project from the root project directory.
更多推荐
Meteor:我怎么知道数据库什么时候准备好?
发布评论