【问题标题】:Exception in template helper: TypeError: Cannot read property 'profile' of undefined模板助手中的异常:TypeError:无法读取未定义的属性“配置文件”
【发布时间】:2014-11-03 16:37:15
【问题描述】:

现在我在收到此错误之前遇到了类似的问题:

模板助手中的异常:TypeError:无法读取属性 未定义的“个人资料”

同样的事情再次发生,但在第二个订单上,其中包含另一个用户配置文件信息(第一个配置文件已定义)。 我如何让它在 {{#each orders}} 中重新渲染?

当只有 2 个订单时,由于某种原因,似乎 info.firstName、lastName 和 building 被调用了 3 次...

在 HTML 中:

<template name="orderItem">
  <section>
    <form role="form" id="ordersList">
      <div>
        {{#each orders}}
          <input type="text" name="name" value="{{info.firstName}} {{info.lastName}}">
        {{/each}}
      </div>
      <div>
        {{#each orders}}
          <input type="text" name="building" value={{info.building}}>
        {{/each}}
      </div>
      <div>
        {{#each orders}}
          <input type="text" name="featuredDish" value={{featuredDish}}>
        {{/each}}
      </div>
    </form>
  </section>
</template>

在javascript中:

Template.orderItem.orders = function() {
  var todaysDate = new Date();
  return Orders.find({dateOrdered: {"$gte": todaysDate}});
};

Template.orderItem.info = function() {
  var userId = this.userId;
  var user = Meteor.users.findOne(userId)
  var firstName = user.profile.firstName;
  var lastName = user.profile.lastName;
  var building = user.profile.building;

  return {
    firstName: firstName,
    lastName: lastName,
    building: building
  }
};

感谢您的帮助!

【问题讨论】:

  • var user = Meteor.users.findOne(userId);的末尾添加分号
  • 您还在使用自动发布还是为 Meteor.users 集合设置正确的发布?请注意,Meteor 会自动设置一个仅发布当前登录用户的用户名的发布:这不足以满足您的需要。

标签: javascript meteor


【解决方案1】:

此错误是常见问题。 您正在尝试访问未定义的用户对象。 函数info 不检查user 是否是正确的对象。使用称为guarding 的技术:

Template.orderItem.info = function() {
  var userId = this.userId;
  var user = Meteor.users.findOne(userId)

  var firstName = user && user.profile && user.profile.firstName;
  var lastName = user && user.profile  && user.profile.lastName;
  var building = user && user.profile  && user.profile.building;

  return {
    firstName: firstName,
    lastName: lastName,
    building: building
  }
};

即使用户是undefined,上面的代码也不会抛出任何错误。

我假设您已删除 autopublish 包。 可能你还没有发布/订阅/订阅Meteor.users 集合,所以在 minimongo 中找不到数据。

记得发布Meteor.users收藏并订阅它:

Meteor.publish("users", function(){
  return Meteor.users.find({},{fields:{profile:1}})
})

Meteor.subscribe("users");

Publish certain information for Meteor.users and more information for Meteor.user

【讨论】:

  • 守卫如何帮助定义“个人资料”。上面的代码消除了错误,但没有解决配置文件未定义的问题。你是说除非他们登录,否则你不能从“Meteor.users”中提取其他用户的个人资料信息?
  • 如果您从 Meteor.users 集合发布文档,则可以访问每个配置文件。默认情况下,没有发布的用户只能访问他的个人资料。
  • 我相信 Meteor 计时可能会在定义变量之前尝试将变量加载到模板中,因此防护至少会抑制错误并保持控制台整洁。与此同时,Meteor 的反应性最终会加载变量并正确填充模板。
猜你喜欢
  • 1970-01-01
  • 2019-01-25
  • 2018-12-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-20
  • 2018-03-02
  • 1970-01-01
相关资源
最近更新 更多