Meteor.userId()返回登录用户的值,但meteor.user()在meteor 1.5

时间:2017-10-17 09:52:13

标签: javascript mongodb meteor meteor-blaze

这是html:

<div>
    <span id="login-entrance">{{loginEntranceContent}}</span>
</div>

这是客户端js代码:

loginEntranceContent(){
    if (Meteor.userId()==null) {
        return 'Log in/Sign up';
    } else {
            Meteor.user().emails.address;
    };
},

现在我确信用户已登录,因为当我尝试Meteor.userId()时,它返回当前用户的_id值。但是Meteor.user()结果是未定义的。我假设Meteor.user()结果应该在以后自动更新。所以我等了一会儿,但它在我的Chrome浏览器中都没有更新。

我知道这个问题与DOM在数据准备好之前呈现的事实有关。但我不知道到底发生了什么。

我已经到论坛寻找答案,有一些类似的话题,但没有一个提供明确的解释和简单的解决方案。所以我希望为它开一个新话题是值得的。

仅供参考,为了解决这个问题,我尝试在服务器端制作一个方法:

Meteor.users.findOne({_id:'this.userId'});

并从客户端调用它。它仍然得到未定义的结果....

1 个答案:

答案 0 :(得分:0)

您正在进行null检查,其他&#39; falsy &#39;值检查,你必须正确使用下面的代码,

loginEntranceContent(){
    if (!Meteor.userId()) {
        return 'Log in/Sign up';
    } else if(Meteor.user() && Meteor.user().emails && Meteor.user().emails[0].address){
            return Meteor.user().emails[0].address;
    } else {
        //do something here.
    };
},

并且你没有向我们展示从客户端调用Meteor方法的代码,因为@Jankapunkt建议在服务器端使用如下代码,

Meteor.users.findOne({_id : this.userId});
  

注意:Meteor为管理User-Accounts

提供了一个漂亮的API