我最近开始尝试 meteor 的auth
分支,根据我在哪里调用调用 this.userId() 的 meteor 方法,它将返回 null 或我需要的用户 ID。
更具体地说,当我的 meteor 方法从 Meteor.startup 内部初始化的 coffeescript 类调用时,它有效,但当从 Meteor.publish 内部调用相同的方法时,它不起作用。
流星方法很简单,可能不相关,但以防万一:
Meteor.methods(
get_user_id: ->
return @userId()
)
编辑:似乎人们无法重现我的问题,这是todo auth示例的补丁,应该可以演示它。
diff --git a/examples/todos/server/methods.js b/examples/todos/server/methods.js
index e69de29..d4182a6 100644
--- a/examples/todos/server/methods.js
+++ b/examples/todos/server/methods.js
@@ -0,0 +1,6 @@
+Meteor.methods({
+ get_user_id: function() {
+ console.log(this.userId());
+ return this.userId();
+ }
+});
diff --git a/examples/todos/server/publish.js b/examples/todos/server/publish.js
index 1552c5e..87cb29f 100644
--- a/examples/todos/server/publish.js
+++ b/examples/todos/server/publish.js
@@ -16,6 +16,8 @@ Todos = new Meteor.Collection("todos");
// Publish visible items for requested list_id.
Meteor.publish('todos', function (list_id) {
+ Meteor.call('get_user_id');
+ //console.log(this.userId())
return Todos.find({
list_id: list_id,
privateTo: {
感谢 Eitan 的补丁!
您应该使用 Meteor.userId()
在 Meteor.methods
中检索当前用户的 ID。 :)
这可能很愚蠢: 但是,你登录了吗? (对不起,这是我终于的问题了。
所以最好先检查一下是否登录:
if (this.userId)
console.log(this.userId)
我所知,this.userId()
本身不是反应性的,所以如果你想让其他东西对它做出反应,你需要把它放在一个Session
变量中。因此,从Meteor.startup
你做:
Session.set('userId', this.userId());
然后,在您需要它的地方,您可以改用它:
Session.Get('userId');
这样,当它丢失并因此null
它稍后会填充时。
对我有用。您确定正确获取了Meteor.call
的返回值吗?像这样:
Meteor.call 'get_user_id', (error, result) -> console.log(result)
如果在方法中添加console.log(@userId())
会发生什么情况?