Meteor: Publish function requires a page refresh after user logs in

点点圈 提交于 2019-12-14 04:19:56

问题


I have a meteor app and I'm calling all the publish functions at once in the iron router configuration like below. I only want to return the subscriptions once the user is logged in, so I check Meteor.userId():

Router.configure({
  layoutTemplate: 'layout',
  loadingTemplate: 'loading',
  notFoundTemplate: '404',
  waitOn: function () {
    if (Meteor.userId()) {
      return [Meteor.subscribe('users'),
          Meteor.subscribe('company'),
          Meteor.subscribe('projects'),
          Meteor.subscribe('columns'),
          Meteor.subscribe('cards'),
          Meteor.subscribe('contents'),
          Meteor.subscribe('labels'),
          Meteor.subscribe('notifications')];
    }
  }
});

The publish functions have all the same structure, dependent on user.companyId, like this:

Meteor.publish('cards', function () {
  if (this.userId) {
    const user = Meteor.users.findOne({ _id: this.userId, companyId: { $exists: true } });

    if (user) {
        return Cards.find({ companyId: user.companyId });
    }
  } else {
    this.ready();
  }
});

My problem is, when the user registers, the account is created and the companyId is saved to the user, but when they now login, the only way for the data to show up is to refresh the browser. I want it to be reactive.


回答1:


From the meteor guide:

On the client, if anything in a reactive function changes, the whole function will re-run, and the results are fairly intuitive.

On the server however, the reactivity is limited to the behavior of the cursors you return from your publish functions. You’ll see any changes to the data that matches their queries, but their queries will never change.

You can indeed use reywood:publish-composite as suggested, but for your simple case I think reactive-publish would be much easier to get up and running.

Install the package, and just wrap your publication in a this.autorun:

Meteor.publish('cards', function () {
  this.autorun( function() {
    if (this.userId) {
      const user = Meteor.users.findOne({ _id: this.userId, companyId: { $exists: true } });

      if (user) {
          return Cards.find({ companyId: user.companyId });
      }
    } else {
      this.ready();
    }
  });
});


来源:https://stackoverflow.com/questions/41605650/meteor-publish-function-requires-a-page-refresh-after-user-logs-in

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!