无法在meteor.JS函数中读取未定义的属性'profile'?

时间:2013-01-01 00:18:45

标签: javascript meteor

我有以下代码:

Template.analyze.userFullName = function() {
    var u = Meteor.users.findOne({_id: this.userId}, {fields: {name: 1}});
    return u.profile.name;
};
在控制台中使用时,

Meteor.users.findOne({_id: this.userId}, {fields: {name: 1}})会返回以下内容:

Object
    _id: "79ef0e67-6611-4747-b669-45cc163cc1d8"
    profile: Object
        name: "My Name"

但是当我在上面的代码中使用它时,我得到了这个:Uncaught TypeError: Cannot read property 'profile' of undefined

为什么会这样?我想要做的就是在他们的个人资料中检索用户的全名并将其传递给模板部分。

1 个答案:

答案 0 :(得分:9)

当用户不可用时,会立即在页面加载时呈现模板,这会导致错误。值得庆幸的是,因为您正在使用被动的Users集合,所以当它可用时,您可以重新呈现它。您可以通过首先检查对象是否为空来执行此操作:

Template.analyze.userFullName = function() {
    // use Meteor.user() since it's available
    if (Meteor.user())
      return Meteor.user().profile.name;
};

这样,当用户为空(在加载期间)时,模板不会抛出错误。在数据可用时,反应性将立即再次调用模板,并在屏幕上呈现。