Meteor 如何处理呈现模板但数据未准备好的情况?

Meteor 如何处理呈现模板但数据未准备好的情况?,meteor,Meteor,在客户端启动中,我订阅了一些内容: Meteor.publish("Roles", function(){ return Roles.find(); }); Meteor.startup(function() { if(Meteor.isClient) { Meteor.subscribe('Roles'); } }); 和角色模板: Template.roles.helper(function() { allRoles: function() { retur

在客户端启动中,我订阅了一些内容:

Meteor.publish("Roles", function(){
  return Roles.find();
});

Meteor.startup(function() {
  if(Meteor.isClient) {
    Meteor.subscribe('Roles');
  }
});
和角色模板:

Template.roles.helper(function() {
  allRoles: function() {
    return Roles.find().fetch();
  }
})

<template name="roles">
  <div>
    {{#with allRoles}}
      <label>{{> role }}</label>
  </div>
</template>
Template.roles.helper(函数(){
所有角色:函数(){
返回角色.find().fetch();
}
})
{{#所有角色}
{{>角色}
问题是,
角色
模板在
角色
准备就绪之前呈现


如何处理这种情况?

您可以在模板上进行订阅,然后使用
模板。subscriptionReady
帮助程序创建一个条件,以在加载订阅时显示加载面板,如下所示:

Template.roles.onCreated(function () {
  this.subscribe("Roles");
});

Template.roles.helper(function() {
  allRoles: function() {
    return Roles.find().fetch();
  }
})

<template name="roles">
  <div>
    {{#if Template.subscriptionsReady}}
      {{#with allRoles}}
      <label>{{> role }}</label>
    {{else}}
      Loading...
    {{/if}}
  </div>
</template>
Template.roles.onCreated(函数(){
本协议。认购(“角色”);
});
Template.roles.helper(函数(){
所有角色:函数(){
返回角色.find().fetch();
}
})
{{{#if Template.subscriptionsReady}
{{#所有角色}
{{>角色}
{{else}
加载。。。
{{/if}

这将替换您的其他订阅,这些订阅可以添加到每个模板的每个onCreated方法中,以便每个模板都有订阅。

有一些常见的处理方法。您可以使用防护装置或iron router的
waitOn
功能。使用guard,只有在获得任何结果时,才从帮助器返回数据:

allRoles: function() {
    var roles = Roles.find();
    //explicit version
    if (roles.count()) return roles

    //implicitly works as well here because you're returning null when there are no results
    return roles
}
在本例中不需要fetch(),因为#with与游标一起工作。如果您遇到由于返回部分数据而需要首先获取的情况,请先检查是否有结果,然后才返回结果


如果您将iron router作为路由的一部分使用,您也可以使用iron router的选项。

这是可行的,但我会在多个位置(URL)使用此角色模板,因此每次在这些URL之间切换时,都会创建角色模板并订阅
角色
,服务器每次都会发布
角色。但是角色集合只需要发布一次,因为角色的内容是固定的。我怎样才能解决这个问题?你的路由是怎么做的?使用
iron router
,但我不想使用
waitOn
,因为在每个路由中,我必须编写相同的
waitOn:function(){return Meteor.subscribe('Roles');}
。你不必在每个路由上都编写它,你可以这样做:
router.configure({waitOn:function()){Meteor.subscribe('roles');}}});
如果我切换路由会发生什么?服务器会每次发布
角色吗?