用流星铁路由器刷新页面

Refreshing page with meteor iron router

这是问题所在:

我目前正在根据在 github (https://github.com/sasikanth513/chatDemo) 上找到的内容编写聊天应用程序 我正在用 iron-router 重构它。

当我转到该页面(单击 link)时,我得到了一个现有的聊天室(这就是我想要的) 当我刷新页面 (F5) 时,我得到了一个新创建的聊天室! (我想要的是获得现有的聊天室...)

这是 ironrouter 中的代码:

Router.route('/chatroom', {
  name: 'chatroom',
  data: function() {

    var currentId = Session.get('currentId'); //id of the other person
    var res=ChatRooms.findOne({chatIds:{$all:[currentId,Meteor.userId()]}});
    console.log(res);
    if(res){
      Session.set("roomid",res._id);
    }
    else{
      var newRoom= ChatRooms.insert({chatIds:[currentId, Meteor.userId()],messages:[]});
      Session.set('roomid',newRoom);
    }

  }
});

您可以在整个项目中找到我的 github 存储库:https://github.com/balibou/textr

非常感谢!

在 meteor 中,Session 对象在客户端启动时为空,loading/refreshing 页面通过 HTTP "restarts" 客户端。要处理此问题,您可以将用户的通讯员 ID 保存在 Meteor.user 属性中,这样您就可以轻松地执行以下操作:

Router.route('/chatroom', {
  name: 'chatroom',
  data: function() {
    var currentId = Meteor.user().profile.correspondentId;
    var res=ChatRooms.findOne({chatIds:{$all:[currentId,Meteor.userId()]}});
    console.log(res);
    if(res){
      Session.set("roomid",res._id);
    }
    else{
      var newRoom= ChatRooms.insert({chatIds:[currentId, Meteor.userId()],messages:[]});
      Session.set('roomid',newRoom);
    }
  }
});

如果有适当的权限,这会起作用,但我建议不要在客户端直接更新该值(我不知道您是否希望用户能够覆盖他们的 correspondentId)。因此,如果您想保护此过程,请将所有代码替换为服务器方法调用,这样您的更新会更安全。

David Weldon 给出了另一个(更常见的情况)解决方案,如果您不介意在您的 URL 中使用 ID(因此没有一个 url)

您的路线数据取决于 Session 变量,这些变量将在刷新后被删除。您有几种选择,但最简单的方法是将房间 ID 直接放入路线中:'/chatroom/:_id'。然后您可以使用 this.params._id 来获取适当的 ChatRooms 文档。请注意,对于房间不存在的情况,您仍然可以保留 '/chatroom',但是您需要在插入后重定向到 '/chatroom/:_id'