发布和订阅单个对象流星JS(Publish and subscribe to a single ob

2019-09-28 03:50发布

如何发布单一对象似乎不够清晰。 请有什么处理的最佳方式。 这段代码并不显示在视图上任何东西。

辅助文件

singleSchool: function () {
   if (Meteor.userId()) {
      let myslug = FlowRouter.getParam('myslug');
      var subValues = Meteor.subscribe('SingleSchool', myslug );
        if (myslug ) {
          let Schools = SchoolDb.findOne({slug: myslug});
          if (Schools && subValues.ready()) {
             return Schools;
          }
       }
   }    
},

发布文件

Meteor.publish('SingleSchool', function (schoolSlug) {
  check( schoolSlug, Match.OneOf( String, null, undefined ) );
    user = Meteor.users.findOne({_id:this.userId})
  if(user) {
    if(user.emails[0].verified) {
      return SchoolDb.findOne({ slug: schoolSlug, userId: {$lt: this.userId}});
    } else {
      throw new Meteor.Error('Not authorized');
      return false;
    }
  }
});

模板文件

<template name="view">
  {{#if currentUser}}
    {{#if Template.subscriptionsReady }}
      {{#with singleSchool}}
        {{singleSchool._id}}
        {{singleSchool.addschoolname}}
      {{/with}}
    {{/if}}
  {{/if}}
</template>

Answer 1:

当你说:“ 这段代码并不显示在视图上任何东西。”好了,里面Meteor.publish你需要返回cursor ,不是array或任何其他object

因此,使用此代码:

Meteor.publish('SingleSchool', function (schoolSlug) {
  check( schoolSlug, Match.OneOf( String, null, undefined ) );
  var user = Meteor.users.findOne({_id:this.userId});
  if(!user || !user.emails[0].verified) {
        throw new Meteor.Error('Not authorized');
    }
    return SchoolDb.find({ slug: schoolSlug, userId: {$lt: this.userId}},{limit:1});
});

我肯定会推荐你去通过如何避免常见错误



Answer 2:

当我只关心单个对象,我实现这个用流星方法:

Meteor.methods({
    "getSingleSchool":function(schoolSlug) {
        //... check args and user permissions
        return SchoolDb.findOne({ slug: schoolSlug, userId: {$lt: this.userId}});
    },
});

然后在模板我跑在onCreated自动运行此付款方式:

Template.view.onCreated(function(){
    const instance = this;
    instance.state = new ReactiveDict();

    instance.autorun(function(){
        let my slug = FlowRouter.getParam('myslug');

        // load if no loaded yet
        if (my slug && !instance.state.get("singleSchool")) {
            Meteor.call("getSingleSchool", mySlug, function(err, res){
                //handle err if occurred...
                this.state.set("singleSchool", res);
            }.bind(instance)); //make instance available
        } 

    });
});

助手然后就返回一个值,如果学校被加载:

singleSchool: function () {
   return Template.instance().state.get("singleSchool");   
},


文章来源: Publish and subscribe to a single object Meteor js