【问题标题】:This this.userId() often null when calling from inside a meteor method从流星方法内部调用时,this.userId() 通常为空
【发布时间】:2012-06-24 18:22:12
【问题描述】:

我最近开始尝试流星的auth 分支,根据我调用调用 this.userId() 的流星方法的位置,它将返回 null 或我需要的用户 ID。

更具体地说,当我从 Meteor.startup 内部初始化的咖啡脚本类调用我的流星方法时,它可以工作,但当从 Meteor.publish 内部调用相同的方法时不起作用

meteor 方法很简单,可能不相关,但以防万一:

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.call 是否打算在服务器端使用?我不确定,但这可能是这里的问题。
  • @TomColeman -- 如果您不相信我,请查看documentation
  • 是的,我想这是一个错误。我想你应该在 github 上打开一个问题并让开发人员知道。显然,此时 auth 分支是未发布的代码...
  • 太好了,谢谢!我只是想在打开问题之前确定一下。

标签: meteor


【解决方案1】:

您应该使用Meteor.userId() 来检索Meteor.methods 中的当前用户ID。 :)

【讨论】:

    【解决方案2】:

    这可能很愚蠢:但是,你登录了吗?(抱歉,这是我的问题。)


    所以最好先检查是否登录:

    if (this.userId)
        console.log(this.userId)
    

    【讨论】:

      【解决方案3】:

      this.userId() 据我所知,它本身没有反应性,所以如果你想让其他东西对它做出反应,你需要把它放在一个 Session 变量中。所以,从Meteor.startup 你可以:

      Session.set('userId', this.userId());
      

      然后,您可以在需要的地方使用它:

      Session.Get('userId');
      

      这样,当它丢失时,null 将在稍后填写。

      【讨论】:

      • 我不认为这是我的问题,我说这个类是从启动内部启动的,但是该函数是定期调用的,没有反应性的期望。
      • 虽然这违背了 Meteor 的概念,但您希望事情是反应性的,而不是定期调用函数;如果仍然继续,为什么不检查它是否为空,在这种情况下跳过执行,直到下一次调用函数。
      • 我认为你错过了理解,我将课程与其他地方的反应性挂钩,但这无关紧要。
      【解决方案4】:

      它对我有用。您确定您正确获得了Meteor.call 的返回值吗?比如:

      Meteor.call 'get_user_id', (error, result) -> console.log(result)

      如果在方法中添加console.log(@userId()) 会发生什么?

      【讨论】:

      • null 结果来自于流星方法内部的日志。
      • 我会尝试为 todo 示例制作补丁以帮助减少问题。
      猜你喜欢
      • 2015-07-18
      • 1970-01-01
      • 1970-01-01
      • 2016-08-24
      • 1970-01-01
      • 1970-01-01
      • 2020-02-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多