如何在流星的发布功能中登录用户电子邮件?

gam*_*ers 3 meteor

我创建了一个流星0.5.4应用程序 - 添加了帐户-ui,帐户密码,并添加了{{loginButtons}}到模板名称="你好"块帽子随每个流星创建库存.

当我在Chrome浏览器控制台输入这个,Meteor.user()电子邮件[0].地址按照这些所谓的来源- http://goo.gl/MTQWu,http://goo.gl/Cnbn7 -我得到当前登录的用户电子邮件.

当我尝试将相同的代码放在if(Meteor.isClient)部分中时:

Template.hello.greeting = function () {
   return Meteor.user().emails[0].address;
};
Run Code Online (Sandbox Code Playgroud)

我明白了:

 Uncaught TypeError: Cannot read property '0' of undefined foo.js:3
 Exception from Meteor.flush: TypeError: Cannot call method 'firstNode' of undefined
Run Code Online (Sandbox Code Playgroud)

如果你不能在发布功能中放置Meteor.user(),我怎样才能收到登录用户的电子邮件?我已经尝试将它作为一个共享函数,并在客户端函数中使用Meteor.call('getEmail',Meteor.userId())调用它,结果类似.

Rah*_*hul 9

模板是被动的.这意味着当页面加载时,模板会运行,并且当其依赖数据源发生更改时,它将再次运行.在你的情况下,它第一次运行时还Meteor.user()没有准备好,所以它还没有emails属性,这会导致错误.要解决此问题,您需要检查用户对象是否仍然存在:

Template.hello.greeting = function() {
  var user = Meteor.user();
  if (user && user.emails)
    return user.emails[0].address;
}
Run Code Online (Sandbox Code Playgroud)

要使当前用户进入发布功能,请使用this.userId.