直接访问url时,未定义Meteor.user()

时间:2015-05-21 05:05:26

标签: meteor

我有一个网址http://localhost:3000/test

Template.test.onRendered(function() {
   console.log(Meteor.user());
});

如果我先打开http://localhost:3000/,然后点击test链接,我会打印Meteor.user()

但如果我直接打开http://localhost:3000/test(在Chrome的地址栏中输入网址并按Enter键),则Meteor.user()未定义。

为什么?

1 个答案:

答案 0 :(得分:1)

这是因为Meteor登录过程在您的应用首次加载时不是即时的,在用户实际连接之前通常需要几毫秒,因此Meteor.user()在模板中返回undefined onRendered生命周期事件。

我不确定您要尝试实现的目标,但您可以通过在onRendered处理程序中引入反应来解决此问题:

Template.test.onRendered(function() {
  this.autorun(function(){
    console.log(Meteor.user());
  });
});

使用Tracker.autorun声明反应计算将允许您的代码在Meteor.user()的值更新时重新运行,特别是在初始登录恢复过程中。