Meteor发布和订阅不起作用

Meteor publish and subscribe not working

本文关键字:不起作用 Meteor      更新时间:2023-09-26

我有一个相当新手的问题,希望有人能帮我。

我有以下代码,其中订阅/发布不起作用:

if (Meteor.isServer) {
  Meteor.publish('items', function () {
     return Items.find({});
   });
}

if (Meteor.isClient) {
  Meteor.subscribe("items");
}

在我的模板中:

<template name="items">
  <div class="ui segment">
   <div class="ui relaxed list">
     {{#each item in items}}
     <div class="item">
        <img class="ui avatar image" src="http://placehold.it/20x20">
           <div class="content">
             <a class="header">{{item.text}} 
           </div>
           <button class="delete">&times;</button>
      </div>
      {{/each}}
   </div>
  </div>
</template>

但什么都得不到输出。然而,当我添加:

 Template.items.helpers({
      items: function () {
        return Items.find({});
      }
    });

我确实看得很清楚。为什么会这样?此外,我也很困惑,为什么有人想将订阅/发布与模板助手一起使用。

我建议您阅读从数据库到UI的数据流:Meteor 的三层

您正在创建一个标记为:items的出版物。那么您正在订阅一个名为deals的出版物。这将不起作用,因为标签必须匹配才能使订阅起作用。

如果添加template helper然后在UI中显示数据,则应用程序中必须有autopublish包。它将是自动发布,而不是您的pub/sub,向客户端发送客户端放入其mini-mongo Items集合中的数据。

所以pub/sub从服务器获取数据到客户端,但不显示。这就是为什么你需要template helper,将客户端的mini-mongo集合中的数据转换为模板所需的格式。

您必须使用与publish()中使用的名称相同的名称subscribe()。在您的情况下(注意"项目"):

/服务器:

Meteor.publish('items', function () {
   return Items.find({});
});

/客户端:

if (Meteor.isClient) {
  Meteor.subscribe('items');
}

发布/订阅链接告诉meter将"Items"集合中的所有文档发送到客户端上的minimongo。现在,模板助手的目的是告诉Metroel,每当文档在Items中发生更改时,您都希望反应性地更新模板。

关于这个主题的一个很好的参考:https://www.discovermeteor.com/blog/understanding-meteor-publications-and-subscriptions/