2013-12-10 190 views
0

我想写一个简单的方法,将返回登录用户的电子邮件(或任何其他字段)。我有自动发布关闭,但每当我尝试访问Meteor.user()在我的displayField方法,我得到未定义。但是,如果我编写一个通用函数(在Meteor之外),它可以访问它并显示它很好......我做错了什么?无法访问流星Meteor.methods中的Meteor.user()

Meteor.methods({ 
displayEmail: function() { 
var user = Meteor.user(); 
if (!user) 
    throw new Meteor.Error(401, "you need to be logged in"); 
console.log(user.emails[0].address); 
return user.emails[0].address; 
} 
}); 

我的客户端功能:

Template.hello.greeting = function() { 
var output = Meteor.call('displayEmail', function(error,id) { 
if (error) 
    return alert(error.reason); 
}); 
return output; 
}; 

我的模板: ... {{greeting}} ...

所以就像我说的,在执行console.log(user.emails [0]。地址)工作得很好,但我在我的模板中得到一个空白...

+1

你可以发布你的代码和你正在使用什么版本的流星?这在0.6.6.3上适合我。 –

+1

您对'Meteor.call'的调用是异步的,这就是'output'为空的原因。您正在查找的电子邮件地址在您的回拨中以'id'提供。为了将其纳入您的模板,请看看这些类似的问题w /答案:http://stackoverflow.com/questions/16540328/meteor-template-helper-conditional-returns-false-consistently和http:// stackoverflow。 COM /问题/ 16632050 /流星返回异步功能到车把模板。 –

+0

我有一种感觉,它与此有关......你有任何链接来阅读关于异步/同步吗? –

回答

0

使用自动发布功能时,您必须实际发布用户才能访问该数据。

Autopublish会自动发布给你,但对于生产使用来说通常是一个坏主意。当你关闭它时,你告诉流星,你将处理所有需要的发布。

例子:

Meteor.publish("currentUser", function() { 
    return Meteor.users.find({_id: this.userId}); 
}); 
+0

这很奇怪..我有自动发布,我没有Meteor.users发布或订阅激活,但如果我去我的Meteor.methods console.log(Meteor.user()..)它会显示。 –

+0

无论是否自动发布,'accounts-base'软件包都会发布当前用户(仅用户名,电子邮件和个人资料字段)。如果使用autopublish包,它会自动发布其他用户。请参阅[第562-635行](https:// github。COM /流星/流星/ BLOB/devel的/包/帐户基/ accounts_server.js#L562)。 – sbking

+0

但为什么我无法从方法中返回用户电子邮件?我可以从方法得到它到console.log,但我不能让它在我的客户端函数中输出... –

0

只是回答我自己的问题,这样下去,奥列格是正确的,你需要在Meteor.call回调函数来获取可变后的异步调用。

所以我Meteor.call部分应该是这样的:

Meteor.call('displayEmail', function (error, result) { 
    Session.set("displayEm",result); 
}); 
return Session.get("displayEm"); 

换句话说,回调函数需要设置一个会话变量(即反应)。 Meteor.method的'return'是回调函数的结果(我知道基本的JS)。