获取当前用户电子邮件流星



我在Meteor中获取当前用户的电子邮件时遇到了一些困难。

发布.js

Meteor.publish('allUsers', function(){
if(Roles.userIsInRole(this.userId, 'admin')) {
return Meteor.users.find({});   
    }
});
Meteor.publish('myMail', function(){ {
    return Meteor.user().emails[0].address; 
    }
});

简介.html

<template name="Profile">
    <h1> My Profile </h1>
    {{#if currentUser}}
<p>{{currentUser.profile.firstName}}</p> <p>{{currentUser.roles}}</p>
<p>{{currentUser.userEmail}}</p>
{{/if}}
</template> 

简介.js

Template.Profile.helpers({
    users: function() {
        return Meteor.users.find();
    },
    userEmail: function() {
        return Meteor.user().emails[0].address;
        }
});

名字和._id显示正常,不幸的是电子邮件地址没有。有人有小费吗?谢谢!

您的'myMail发布既多余又不正确。您应该返回游标(或游标数组(,或者观察游标并自己发送处理发布生命周期(一个相当高级的功能,与您的问题无关(。您正在使用它 a-la Meteor.methods ,无论如何您都不应该在出版物中真正使用Meteor.user()

这是多余的,因为 Meteor 的帐户包会自动发布当前用户的emails字段。

在模板中,您将userEmail视为当前用户的属性,而不是将其作为帮助程序调用。

我建议使用警卫并确保用户实际上有一个电子邮件地址,如下所示:

.JS:

Template.Profile.helpers({
  users: function() {
    return Meteor.users.find();
  },
  userEmail: function(user) {
    if (user.emails && user.emails.length > 0) {
      return user.emails[0].address;
    }
    return 'no email';
  }
});

.HTML:

<template name="Profile">
    <h1> My Profile </h1>
    {{#if currentUser}}
    <p>{{currentUser.profile.firstName}}</p> <p>{{currentUser.roles}}</p>
    <p>{{userEmail currentUser}}</p>
    {{/if}}
</template>

我还强烈建议不要在'allUsers'发布中发布所有字段,因为它会暴露几乎在任何情况下都不应离开服务器的敏感数据(例如密码数据(。

最新更新