我创建了一个流星0.5.4应用程序 - 添加了帐户-ui,帐户密码,并添加了{{loginButtons}}到模板名称=“hello”块帽子随每个流星创建库存。
当我在Chrome浏览器控制台中键入此内容时,Meteor.user()。电子邮件[0]。地址根据这些SO来源 - http://goo.gl/MTQWu,http://goo.gl/Cnbn7 - 我获取当前登录的用户电子邮件。
当我尝试将相同的代码放在if(Meteor.isClient)部分中时:
Template.hello.greeting = function () {
return Meteor.user().emails[0].address;
};
我明白了:
Uncaught TypeError: Cannot read property '0' of undefined foo.js:3
Exception from Meteor.flush: TypeError: Cannot call method 'firstNode' of undefined
如果你不能在发布功能中放置Meteor.user(),我怎样才能收到登录用户的电子邮件?我已经尝试将它作为一个共享函数,并在客户端函数中使用Meteor.call('getEmail',Meteor.userId())调用它,结果类似。
答案 0 :(得分:9)
模板是被动的。这意味着当页面加载时,模板会运行,并且当其依赖数据源发生更改时,它将再次运行。在您的情况下,第一次运行时,Meteor.user()
尚未就绪,因此它还没有emails
属性,这会导致错误。要解决此问题,您需要检查用户对象是否存在:
Template.hello.greeting = function() {
var user = Meteor.user();
if (user && user.emails)
return user.emails[0].address;
}
要将当前用户置于发布功能中,请使用this.userId
。