获取当前用户邮箱 meteor

Get current user email meteor

我在 Meteor 中获取当前用户的电子邮件有点困难。

publish.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; 
    }
});

profile.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> 

profile.js

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

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

您的 'myMail 出版物既多余又不正确。您应该 return 一个游标(或一个游标数组),或者观察一个游标并自己发送处理发布生命周期(一个相当高级的功能,与您的问题无关)。你正在使用它 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' 出版物中的所有字段,因为它会暴露几乎在任何情况下都不应离开服务器的敏感数据(例如,密码数据)。