5

我有以下代码:

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

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

4

1 回答 1

9

The Template is being rendered immediately on pageload when the user is not available yet, which is causing an error. Thankfully since you're using the Users collection, which is reactive, you can just have it re-render when it becomes available. You do this by checking first if the object is not null:

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

This way, when the user is null (during load) the Template won't throw an error. Immediately upon the data being available, the reactivity will invoke the template again, and it will render on the screen.

于 2013-01-01T00:56:37.693 回答