Accessing currentUser in Angularjs -
i have following code in app.js
config used on secure routes:
var checkloggedin = function($q, $timeout, $http, $location, $rootscope){ // initialize new promise var deferred = $q.defer(); // make ajax call check if user logged in $http.get('/api/loggedin').success(function(user){ // authenticated if (user !== '0') $rootscope.user = user; //is advisable??? $timeout(deferred.resolve, 0); // not authenticated else { $timeout(function(){deferred.reject();}, 0); $location.url('/login'); } }); return deferred.promise; };
the end returns user object.
i able access current user different controllers , wondered whether should make use of $rootscope
(as shown above) or whether service
way go.
any code samples appreciated if service way forward.
if want use user variable in views, reading rootscope fine. however, if in controller want use user something, can't read directly rootscope, variable may not yet have been set checkloggedin
function.
for instance, if have code in controller
.controller('navbarctrl', function ($scope, $rootscope) { if ($rootscope.user) { // logged in stuff } //...
it may fail, promise has not yet set user variable in rootscope.
it's bit annoying, guarantee variable set, 1 need reed promise. try access logged in user through service.
.service('personservice', function ($http) { return { getcurrentuser: function() { return $http.get('/api/person/me', {cache: true}); // or can use similar code above } } });
is example. can see, have enabled cache, multiple calls function not create new calls end.
then use this:
.controller('navbarctrl', function ($scope, personservice) { personservice.getcurrentuser().success(function(user) { $scope.user = user; // or maybe else $scope.showbutton = user.permissionlevel > 5; }); // .....
Comments
Post a Comment