【问题标题】:Meteor.js how to get the userId inside an onStop event?Meteor.js 如何在 onStop 事件中获取 userId?
【发布时间】:2016-08-09 06:42:01
【问题描述】:

我在我的 meteor.js 服务器上运行它:

Meteor.publish('games', function(){

    this.onStop(function() {
        Meteor.call('leaveQueue');
    });

    return Games.find({ player: this.userId })
});

当用户停止订阅时,它会调用 methods.js 上的这个函数:

Meteor.methods({

    leaveQueue:function(){
        console.log(this.userId);
    }

});

它将 null 记录为 userId.. 现在,如果我在控制台上使用 Meteor.call('leaveQueue') 从前端调用它,它会正确记录用户 ID。

我什至试过console.log(Meteor.userId)和console.log(Meteor.userId()),都是null。

会发生什么?

【问题讨论】:

    标签: javascript meteor


    【解决方案1】:

    Meteor 允许您从服务器端的另一个 Method 调用 Method,并维护正确的上下文(因此 userIdconnection 等都取自原始 Method 调用)。但是,从发布函数调用方法时并非如此。当您在出版物中创建Meteor.call 时,被调用的方法会尝试从当前 DDP 连接中提取userId 详细信息(通过查看内部DDP._CurrentInvocation)。这些细节不存在,因此被调用的方法无法保留它们(更多信息,请参阅ddp-server/livedata_server.js 来源)。

    话虽如此,您可以在您的出版物的onStop 回调中获取当前的userId

    Meteor.publish('games', function games() {
      this.onStop(() => {
        // This will log the proper userId
        console.log(this.userId);
      });
      return Games.find({ player: this.userId })
    });
    

    我建议通过调用实用程序函数而不是 Meteor 方法,在 onStop 回调中使用 userId 运行您的方法代码。如果您想避免重复代码,您可以将您的方法的公共代码提取到一个实用函数中,并在两个地方都使用它。例如:

    // Stored in a utility file somewhere
    function doSomethingCommon(userId) {
      // Do something ...
    }
    
    Meteor.methods({
      leaveQueue() {
        doSomethingCommon(Meteor.userId());
      }
    });
    
    Meteor.publish('games', function games() {
      this.onStop(() => {
        doSomethingCommon(this.userId);
      });
      return Games.find({ player: this.userId })
    });
    

    【讨论】:

      猜你喜欢
      • 2010-12-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-18
      • 2013-04-27
      • 1970-01-01
      • 2021-05-08
      相关资源
      最近更新 更多