onCreated中未定义Meteor.connection._lastSessionId

时间:2016-08-22 14:27:57

标签: meteor meteor-blaze

所以我有这个代码人员

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在onCreated事件中返回undefined。但是,如果我尝试点击事件,它可以正常工作。为什么会引起这种情况,这是一个解决方法?

2 个答案:

答案 0 :(得分:1)

您尝试在连接收到会话ID之前记录会话ID。例如,将您的通话包裹在setTimeout

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

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

答案 1 :(得分:0)

在最初创建模板时,客户端上基本上_lastSessionId尚未提供Meteor.call("updateHistory", {clientIp,clientConnId,visitedOne}, callback) (它可能是您应用中呈现的第一个模板)。但是,由于您无论如何都要调用服务器方法,因此无需在客户端上获取此信息,只需将变量直接用于已存在的变量即可!

简化:

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

为:

this.connection.id

并获取clientIp(如有必要)并在服务器上使用{{1}}。

相关问题