使用用户名值设置会话

Set Session with usernames value

我尝试查询当前登录的用户名并将值设置为会话。最后,它似乎可以正常工作,但在浏览器控制台中我得到以下异常: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

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

在您的用户完全登录之前,您的助手是 运行。您可以通过添加 guard 来避免错误,如下所示:

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

但是,您真的不应该首先这样做,因为助手应该没有副作用 - 请参阅 common mistakes 的 'overworked helpers' 部分。

相反,您可以在代码中需要用户名的任何地方使用 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. 它适用于 browsers/machines - 我假设您想跟踪用户在任何地方登录,而不是跟踪特定用户使用同一浏览器再次登录。