【问题标题】:meteor .publish on server side: working with a client variable服务器端上的流星 .publish:使用客户端变量
【发布时间】:2016-06-06 20:27:31
【问题描述】:

我正在建立一个聊天室,根据当前用户选择的聊天室,我想用这个功能发布消息:

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

现在 chatId 仍然是硬编码的,但它需要是动态的。 chatId 在 URL 中传递(例如.../chat/QMMjBgCvLcnLvJPvx)。在基于客户端的代码中,我曾经阅读过chatId

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

铁路由器

但这在服务器端不起作用。有没有办法将chatId 从 URL 发送到服务器,所以我如上所述使用 Meteor.publish。任何帮助表示赞赏:)

【问题讨论】:

  • 订阅发布时可以传入参数。

标签: meteor chat publish-subscribe


【解决方案1】:

订阅时传入变量,即

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

在出版物中:

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

【讨论】:

    【解决方案2】:

    在您的路由中,您可以订阅发布并在 waitOn 中传递一个参数,这将导致应用显示您的加载模板,直到订阅准备好并且 chatId 将是响应式的。

    配置加载模板:

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

    您的路线:

    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})
                }
            })
        }
    });
    

    出版:

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

    【讨论】:

      【解决方案3】:

      感谢您的回答和提示。经过一些更多的修改后,我得到了这个,它解决了这个问题:

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

      【讨论】:

        猜你喜欢
        • 2015-09-24
        • 2015-12-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-09-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多