【问题标题】:Publish/subscribe not loading in Blaze template发布/订阅未加载到 Blaze 模板中
【发布时间】:2017-05-02 16:07:51
【问题描述】:

在我实现发布/订阅之前,我的代码运行良好。我关注了the basic tutorial 并检查了the source code,但我没有做任何不同的事情。一切都构建并运行,但 MongoDB 中的任何内容都不会显示在 Blaze 模板中。

imports/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({});
  }
});

【问题讨论】:

    标签: meteor meteor-blaze


    【解决方案1】:

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

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

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

    另外,请参阅Meteor Subscribe & Publish with external api

    【讨论】:

    • 不幸的是,这似乎没有任何作用。我还尝试了几种变体,包括使用Meteor.subscribe 而不是Features.find({})
    【解决方案2】:

    试试这个:

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

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

    【讨论】:

    • 感谢您的回答,不幸的是这不起作用。我还尝试使用this.autorunthis.subscribeMeteor.autorunMeteor.subscribe
    【解决方案3】:

    我看到您正在使用导入目录。您是否记得将您的发布文件导入到 server/main.js 文件中?

    服务器/主服务器:

    import 'imports/path/to/publications.js'
    

    【讨论】:

    • 是的,import { Features } from '../imports/api/features.js';
    • 不,那是您导入您的收藏。您需要将保存发布位置的文件导入服务器。您可以使用我的答案中的行来做到这一点。如果您不这样做,则该出版物未在服务器上注册,并且流星将无法运行它。我怀疑这是你的问题
    猜你喜欢
    • 2016-12-14
    • 1970-01-01
    • 1970-01-01
    • 2012-07-01
    • 1970-01-01
    • 2017-12-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多