meteor .publish บนฝั่งเซิร์ฟเวอร์: ทำงานกับตัวแปรไคลเอนต์

ฉันกำลังสร้างแชทและขึ้นอยู่กับห้องแชทที่เลือกโดยผู้ใช้ปัจจุบัน ฉันต้องการเผยแพร่ข้อความด้วยฟังก์ชันนี้:

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 ตามที่กล่าวไว้ข้างต้น ความช่วยเหลือใด ๆ ที่ชื่นชม :)


person janjackson    schedule 06.06.2016    source แหล่งที่มา
comment
คุณสามารถส่งพารามิเตอร์ได้เมื่อคุณสมัครรับข้อมูลสิ่งพิมพ์   -  person L4zl0w    schedule 07.06.2016


คำตอบ (3)


ส่งผ่านตัวแปรเมื่อคุณสมัครสมาชิกเช่น

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

ในสิ่งพิมพ์:

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

ในเส้นทางของคุณ คุณสามารถสมัครรับข้อมูลสิ่งพิมพ์และส่งพารามิเตอร์ภายใน 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});
});
person Luna    schedule 07.06.2016

ขอบคุณสำหรับคำตอบและคำแนะนำของคุณ หลังจากแก้ไขเพิ่มเติม ฉันมาถึงสิ่งนี้ ซึ่งแก้ไขปัญหาได้:

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