Meteor.connection._lastSessionId 在 onCreated 中未定义

Meteor.connection._lastSessionId is undefined in onCreated

所以我有这段代码伙计们

Template.mainLayout.onCreated(function () { //HERE
  console.log("mainLayout created");
  var context = FlowRouter.current();
  // use context to access the URL state
  console.log(context);
  var visitedOne = context.path;

  //getting the connID

  var clientIp = headers.getClientIP(); // no need for this anymore
  var clientConnId = Meteor.connection._lastSessionId; // HERE
  console.log(clientIp);
  console.log(clientConnId); //HERE
  // console.log(Meteor.connection._lastSessionId);



  Meteor.call("updateHistory", {clientIp,clientConnId,visitedOne}, function(error, result){
   if(error){
     console.log("error", error);
 });
   if(result){

   }
  });//Meteor.call
});

我的问题在评论中标出 //HERE

Meteor.connection._lastSessionId returns 在 onCreated 事件中未定义。但是,如果我尝试点击事件,它就可以正常工作。这是为什么造成的,有什么解决方法?

您试图在连接收到会话 ID 之前记录它。例如,将您的电话包装在 setTimeout:

...
setTimeout(() => {
  console.log(Meteor.connection._lastSessionId);
}, 500);
...

您可能需要稍微调整超时值,但它会被记录下来。但是,以这种方式使用 setTimeout 确实不那么可靠,因为设置会话 ID 所需的时间可能会有所不同。您可能需要考虑设置某种简单的轮询以持续检查会话 ID,直到它被设置。

基本上 _lastSessionId 在最初创建模板时客户端尚不可用(它可能是您的应用程序中呈现的第一个模板)。但是,不需要在客户端上获取它,因为无论如何您都在调用服务器方法,只需在变量已经存在的地方直接使用该变量!

所以简化:

Meteor.call("updateHistory", {clientIp,clientConnId,visitedOne}, callback)

至:

Meteor.call("updateHistory", visitedOne, callback)

并获取 clientIp(如果需要)并在服务器上使用 this.connection.id