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

tro*_*ytc 5 javascript meteor

我有以下代码:

Template.analyze.userFullName = function() {
    var u = Meteor.users.findOne({_id: this.userId}, {fields: {name: 1}});
    return u.profile.name;
};
Run Code Online (Sandbox Code Playgroud)

Meteor.users.findOne({_id: this.userId}, {fields: {name: 1}}) 在控制台中使用时返回以下内容:

Object
    _id: "79ef0e67-6611-4747-b669-45cc163cc1d8"
    profile: Object
        name: "My Name"
Run Code Online (Sandbox Code Playgroud)

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

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

Rah*_*hul 9

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

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

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