使用用户名值设置会话

时间:2015-05-02 22:37:05

标签: meteor coffeescript

我尝试查询登录的当前用户名并将值设置为Session。最后,它似乎正在工作,但在浏览器控制台中,我得到以下异常:Exception in template helper: TypeError: Cannot read property 'username' of undefined

Template.dashboard.helpers
  'setUsernameToSession': ->
    user = Meteor.users.findOne(Meteor.userId())
    Session.set 'username', user.username

这是我的第一个问题,我是流星新手。提前谢谢。

1 个答案:

答案 0 :(得分:0)

您的帮助程序在您的用户完全登录之前正在运行。您可以通过添加guard来避免错误:

Template.dashboard.helpers
  'setUsernameToSession': ->
    Session.set 'username', Meteor.user()?.username

然而,你真的不应该首先这样做,因为帮助者应该是无副作用的 - 看看过度工作的助手' common mistakes的一部分。

相反,您可以在需要用户名的代码中的任何位置使用Meteor.user()?.username,而在模板中,您可以使用{{currentUser.username}}而无需帮助程序。这两个示例都是反应性的,因此不需要Session变量。

在您的特定情况下,您希望在用户登录时提醒用户。一种方法是使用autorun,您可以将其放在client目录中的任何位置:

Tracker.autorun (c) ->
  # extract the username
  username = Meteor.user()?.username
  if username
    # replace this with something better
    console.log "Welcome back #{username}!"
    # stop the autorun
    c.stop()

这应该是比使用会话变量更强大的解决方案,因为:

  1. 会话变量在刷新或关闭浏览器后被删除。
  2. 它可以在浏览器/机器上运行 - 我假设你想跟踪用户在任何地方登录,而不是跟踪特定用户使用同一浏览器再次登录。