如何在Iron Router中访问数据

How to reach data within Iron Router?

本文关键字:访问 数据 Router Iron      更新时间:2023-09-26

在我的url为object/:_id的页面上,用户通常应该只访问一个文档,我已经这样设置了:

waitOn: function() {
    return Meteor.subscribe('objects', this.params._id),
},
data: function() {
    return Objects.findOne({_id: this.params._id})
}

然而,也应该可以偷看并使用其他一些对象,,但只能使用与我们正在查看的对象颜色相同的对象,所以我也需要访问这些对象。

以下是我认为有效的方法:

onBeforeAction: function() {
    var self = Objects.findOne({_id: this.params._id})
    var color = self.color
    Session.set('chosenColor', color)
    this.next()
},
waitOn: function() {
    return Meteor.subscribe('objects', Session.get('chosenColor'))
},
data: function() {
    return Objects.findOne({_id: this.params._id})
}

应该注意的是,这在一开始是有效的,但后来突然莫名其妙地停止了工作。由于某种原因,self现在总是"未定义"。

在Iron Router中访问这些数据的正确方法是什么?

这里有循环逻辑:您试图加载一个对象并在订阅将发布该对象的集合之前获取其颜色。只需将颜色逻辑移动到服务器上的发布功能即可。

客户端js:

waitOn: function() {
    return Meteor.subscribe('objects', this.params._id);
},
data: function() {
    return Objects.findOne({_id: this.params._id})
}

服务器js:

Meteor.publish('objects',function(id){
  check(id, Meteor.Collection.ObjectID);
  var self = Objects.findOne({_id: id})
  if ( self ){
    var color = self.color;
    return Objects.find({ color: color });
  }
  else this.ready();
});

在数据中尝试this.ready()条件:

waitOn: function() {
    return Meteor.subscribe('objects');
},
data: function() {
    if (this.ready()) {
        var self = Objects.findOne({_id: this.params._id});
        var color = self.color;
        return Objects.findOne({_id: this.params._id}, color);
    }
}