gpt4 book ai didi

javascript - Meteor:onConnection,检查用户是否登录

转载 作者:太空宇宙 更新时间:2023-11-04 15:54:35 26 4
gpt4 key购买 nike

我正在使用 onConnection Hook 和一些模板助手来执行一些统计操作。但现在,当我是注册用户时,我不想排除这些操作。问题是,我无法在 onConnection Hook 中使用 Meteor.user() ,那么如何检查用户是否已登录?

关于代码,没有太多可展示的

Meteor.onConnection(function(conn) {
if(Meteor.user()) {
console.log("you are logged in")
} else {
console.log("u are not logged in")
}
});

这不是真实的例子,但它简单地显示了我想要做的事情错误

err [Error: Meteor.userId can only be invoked in method calls. Use this.userId in publish functions.]

我知道我可以在方法中使用 Meteor.user(),但是如何在 onConnection 中找到用户是否已登录?

最佳答案

出于统计目的,我建议使用出版物。他们有更复杂的 API,使您可以更好地控制您的连接。

Meteor.publish('users.trackPresence', function() {
// Both this.userId && this.connection are available to be called from here

this.onStop(function(){
// user went offline
});

this.ready();
});

在客户端上,您可以检查用户是否存在,如果是这种情况,甚至不订阅:

Tracker.autorun(function(){
if (!Meteor.userId())
Meteor.subscribe('users.trackPresence');
});

当您从 Tracker.autorun 中订阅时,Meteor 会自动处理取消订阅/重新订阅

在此处了解有关 pubsub api 的更多信息 https://docs.meteor.com/api/pubsub.html

关于javascript - Meteor:onConnection,检查用户是否登录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42814310/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com