janjackson
janjackson

Reputation: 351

meteor .publish on server side: working with a client variable

I am building a chat and based on the chatroom selected by the currentUser, I want to publish messages with this function:

Meteor.publish('messages',function(){
  return Messages.find(
    {chatId: 'QMMjBgCvLcnLvJPvx'},
    sort:{timestamp: -1}
  });
});

Now the chatId is still hardcoded, but it needs to be dynamic. The chatId is passed in the URL(e.g..../chat/QMMjBgCvLcnLvJPvx). In the client based code I have used to read the chatId:

var chatId = Router.current().params._id;

Iron Router

But this doesn't work server side. Is there a way to send the chatId from the URL to the server so I use Meteor.publish as mentioned above. Any help appreciated :)

Upvotes: 2

Views: 206

Answers (3)

janjackson
janjackson

Reputation: 351

Thanks for your answers and the hints. After some more modifications I arrived at this, which solved the issue:

  var chatId = Router.current().params._id
  this.wait(Meteor.subscribe('messages', chatId));

Upvotes: 1

Luna
Luna

Reputation: 1178

In your route, you can subscribe to a publication and pass a param inside waitOn which will cause the app to show your loading template until the subscription is ready and the chatId will be reactive.

Configure loading template:

Router.configure({
    layoutTemplate:'templateName',
    loadingTemplate: 'anotherTemplateName'
});

Your route:

Router.route('/chat/:_id',{
    waitOn: function(){
        return Meteor.subscribe('messages', this.params._id);
    },

    action: function(){
        //render your template with data
        this.render('templateName', {
            data: function () {
                //will return object to the template which you can use in both HTML and JS. Also necessary for the link.
                return Somethings.findOne({_id: this.params._id})
            }
        })
    }
});

Publication:

Meteor.publish("messages", function (chatId) {
    //the chatId comes from our subscribe in our route
    return Messages.find({chatId: chatId});
});

Upvotes: 1

L4zl0w
L4zl0w

Reputation: 1097

Pass in the variable when you subscribe I.e.

Meteor.subscribe("messages", {chatId: Session.get("current-room")})

In the publication:

Meteor.publish('messages',function(chatId){
  return Messages.find(
    {chatId: chatId},
    sort:{timestamp: -1}
  });
});

Upvotes: 1

Related Questions