【问题标题】:Meteor.user() is undefined inside a functionMeteor.user() 在函数内部未定义
【发布时间】:2014-08-26 19:36:07
【问题描述】:

我有这个模板助手

Template.foo.helpers
  'bar':->
    console.log(Meteor.user().profile)
  'baz':->
    console.log(Meteor.user().profile)
  'buzz':->
    console.log(Meteor.user().profile)

它完美地记录了用户对象。

但是当我尝试在模板助手之外使用它时,它会返回一个Uncaught TypeError: Cannot read property 'profile' of undefined

这样

checkProfile=(profile)->
  console.log profile

Template.foo.helpers
  'bar':checkProfile(Meteor.user().profile)
  'baz':checkProfile(Meteor.user().profile)
  'buzz':checkProfile(Meteor.user().profile)

我认为它在加载 Meteor.user() 之前执行该函数,但是当我尝试在 checkProfile 中记录 Meteor.userId 时,例如:

checkProfile=(profile)->
  console.log Meteor.userId()
  console.log profile

甚至

checkProfile=(profile)->
  console.log Meteor.userId()
  console.log(Meteor.user())

它会尽快记录用户 ID,但仍会返回未捕获的错误。

现在我得出结论,Meteor.userId() 在流星开始时始终可用,而Meteor.user() 对象在之后加载?

请识字我的这个结论,因为这些小事情将来可能会成为我代码中的一个大问题。谢谢。

旁注:

我确定用户已登录,因为我正在测试用户登录时的错误测试。只是当页面刷新时,代码运行并在尝试运行 Meteor.user() 时返回该错误

【问题讨论】:

    标签: meteor


    【解决方案1】:

    您的错误是由于尝试访问未定义对象上的“配置文件”引起的。所以它与checkProfile 功能无关。

    模板的 helper 用 Deps.autorun 包裹,这意味着如果您将响应式数据源(如 Meteor.user())放在 helper 中,那么每次更改响应式数据源时都会重新运行 helper。

    考虑在你的助手中使用守卫:

    var user = Meteor.user();
    var profile = user && user.profile;
    if(profile){
      checkProfile(profile);
    }
    

    上述代码将运行几次 - 每次来自 Meteor.user() 的数据都发生更改。

    在这里查看它是如何工作的: http://meteorpad.com/pad/j2bqKeMfuuLpbn2TW

    创建帐户,打开控制台,然后刷新流星应用以查看日志。

    旁注

    您可以检查您是否正在登录:

    if(Meteor.loggingIn()){
      ...
    }
    

    【讨论】:

    • 这是我的问题!
    【解决方案2】:

    您是否有机会在出版物中调用 checkProfile ?如果是这样,您需要使用发布的 this.userId

    【讨论】:

      猜你喜欢
      • 2021-07-07
      • 2014-10-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-22
      • 2018-05-12
      • 2017-08-24
      相关资源
      最近更新 更多