发布/订阅未在Blaze模板中加载

时间:2017-04-27 22:36:48

标签: meteor meteor-blaze

我的代码工作正常,直到我实现发布/订阅。我跟着the basic tutorial并检查了the source code,我没有做任何不同的事情。一切都在构建和运行,但是MongoDB中的任何内容都不会显示在Blaze模板中。

进口/ API / features.js

if (Meteor.isServer) {
   Meteor.publish('features', function featuresPublication() {
      return Features.find({});
   });
   Meteor.publish('comments', function commentsPublication() {
      return Features.find({}, {fields: {comments: 0}});
   })
};

的客户机/ main.js

Template.body.onCreated(function bodyOnCreated() {
  Meteor.subscribe('features'); 
});

的客户机/ main.html中

<body>
  <h1 id="title">Feature Requests</h1>
  {{#if currentUser}}
    <button class="ui green button create" id="create">Add a New     Feature Request</button>
    {{> requestForm}}
    {{#each features}}
      {{> feature}}
    {{/each}}
  {{else}}
    {{> loginButtons}}
  {{/if}}
</body>

编辑#1

在我运行meteor remove autopublish之前,我的代码看起来像这样并且有效:

Template.body.helpers({ 
  features() {
    return Features.find({}, {sort: {createdAt: -1}});
  },
  comments() {
    return Features.find({}, {fields: {comments: 0}}); 
  },
});

编辑#2

感谢所有提供答案的人。我从根本上误解了发布/订阅的工作原理。我没有意识到我订阅后仍需要拨打return Features.find({})。这是我的工作代码:

import { Features } from '../imports/api/features.js';

import '../imports/api/features.js'

Template.body.onCreated(function bodyOnCreated() {
  Meteor.subscribe('features'); 
});

Template.body.helpers({
  features: function() {
    return Features.find({});
  }
});

3 个答案:

答案 0 :(得分:1)

试试这个:

Template.body.onCreated(function() {
  const self = this;
  self.autorun(() => {
    self.subscribe('features');
  });
});

另请参阅https://guide.meteor.com/data-loading.html#organizing-subscriptions

答案 1 :(得分:1)

忽略第一个答案。缺少autorun首先引起了我的注意,但由于你没有将任何参数传递给subscribe,因此不需要它。

我的下一个问题是:在client/main.html中,features的引用来自哪里? features上有Template.body个助手吗?如果没有,您需要添加它:

Template.body.helpers({
  features: function() {
    return Features.find({});
  }
});

另请参阅Meteor Subscribe & Publish with external api

答案 2 :(得分:1)

我看到你正在使用imports目录。您是否记得将您的出版物文件导入server / main.js文件?

服务器/主:

import 'imports/path/to/publications.js'
相关问题