FAQ: how to watch Meteor.userId?
Closed this issue · 7 comments
Hello @lvbreda ,
I could find the way to ask you a question, other then create an issue here,
Say, I want angularjs to react somehow on the Meteor authentication. E.g.: when the user logs in, I want to display user's id:
<p>logged in as {{ user_id }}</p>
LoginCtrl = [
"$scope","$rootScope","$routeParams",
"$location","$timeout",
function($scope,$rootScope,$routeParams,$location,$timeout){
$scope.$watch('Meteor.userId()', function(newValue, oldValue){
$scope.user_id = newValue;
})
}
]
Of course, it's now working (it just shows "logged in as"), but I cannot figure out the way to do it. Can you help?
I'm looking for something like this: (Meteor's addition to Handlebars template system):
// If we're using Handlebars, register the {{currentUser}} and
// {{loggingIn}} global helpers.
if (typeof Handlebars !== 'undefined') {
Handlebars.registerHelper('currentUser', function () {
return Meteor.user();
});
Handlebars.registerHelper('loggingIn', function () {
return Meteor.loggingIn();
});
}
Using Handlebar's analogy I've tried:
//app.js:
app.factory('currentUser', function(){
return Meteor.user();
})
//controllers.js:
LoginCtrl = [
"$scope","currentUser",
function($scope,currentUser){
$scope.user_id = currentUser._id;
}
]
It works only when I manually refresh the browser. :(
this is what's working so far: (based on the "time" example from angular directives)
app.directive('currentUser', function($timeout) {
return function(scope, element) {
var timeoutId; // timeoutId, so that we can cancel the user updates
// used to update the UI
function updateUser() {
element.text((Meteor.user() != null)? Meteor.user()._id : "anonymous");
}
// schedule update in one tenth of a second
function updateLater() {
// save the timeoutId for canceling
timeoutId = $timeout(function() {
updateUser(); // update DOM
updateLater(); // schedule another update
}, 100);
}
// listen on DOM destroy (removal) event, and cancel the next UI update
// to prevent updating user after the DOM element was removed.
element.bind('$destroy', function() {
$timeout.cancel(timeoutId);
});
updateLater(); // kick off the UI update process.
}
});
However, I'm not sure that just polling it every 0.1 second is a good idea.
What do you think?
@alex-okrushko Sorry for the late response, I will try to write some kind of solution here tomorrow. I ran into to the same problem for a project that I'm working on currently.
@lvbreda, looking forward for the solution 👍
@lvbreda any updates on this item as well?
In the client.js of this package i added @ line 6 the following:
if(name == 'users'){
return Meteor.users;
}
After doing that i was able to use the $meteor service in my controllers like:
$scope.currentUser = $meteor('users').find({_id:Meteor.userId()})
What doesn't work is to use findOne as it will not set to the scope variable after the refresh
Irrelevant. Closing.