问题
Thing is I want to check if the user is is logged in via Meteor.user() within onBeforeAction in my routes. Problem is, after a page reload Meteor.user() returns undefined for a split second before it gets loaded.
Here my route config:
Router.map(function() {
this.route('list', {
path: '/list',
template: 'list',
onBeforeAction: function(){
console.log('onBeforeAction');
if(!Meteor.user()){
Router.go('/login');
}
this.next();
}
});
});
I googled a lot and the workarounds with "waitOn" and "return Meteor.user();" doesn't seem to work in my case. Also interesting...locally it works perfectly fine, so I can do a page reload and still stay on the "list" view, but the on Modulus deployed app acts as described above and redirects to the login page.
Any ideas? Thanks in advance.
回答1:
It's better to use !!Meteor.userId()
to check if a user is logged in, because there's no latency while waiting for the user data to be loaded from the server. In fact, Meteor.user
routine is more or less equivalent to:
function () {
return Meteor.users.findOne({ _id: Meteor.userId() });
}
which explains why it may return undefined
even if the user is logged in.
来源:https://stackoverflow.com/questions/32024910/meteor-user-returns-undefined-after-page-reload