How to keep track of current user in angularJS controllers? -
factory / service:
angular.module('phoenix-template') .factory('user', ['$http', function($http){ function current(){ $http.get('http://localhost:4000/api/current_user').then(function(res){ return res.data; }) } this.currentuser = current(); }]); })(); controller:
(function(){ 'use strict'; angular.module('phoenix-template') .controller('navctrl', ['$scope','user', function($scope, user){ $scope.currentuser = user.currentuser; $scope.$watch( 'currentuser', function () { user.currentuser = $scope.currentuser; }); }]); })(); i'm keeping track of current user in backend, want track current user in angular across controllers display purposes, etc..
but, i"m going wrong..
tips, help, appreciated.
i believe getting confused factory , service not same in angular.
- a factory created on every injection
- a service singleton , created once lifetime of angular app.
the service, in case, best choice inject controllers. first 1 access materialize user data server. rest of controllers make use of service use same service instance there no overhead of going server each controller.
here code. service retrieves user using function persists result local field, way ever called once. controller can call function retrieve (or access field directly if add checking logic).
(function(){ angular.module('phoenix-template') .service('nguserservice', ['$http', function($http){ var me = this; function getuser(callback) { // if user has been retrieved not again, return retrieved instance if(me.currentuser) calback(me.currentuser); // retrieve currentuser , set property on service $http.get('http://localhost:4000/api/current_user').then(function(res){ // set result field on service me.currentuser = res.data; // call callback retrieved user callback(me.currentuser); }); } return {getuser:getuser} }]); })(); controller code
(function(){ 'use strict'; angular.module('phoenix-template') .controller('navctrl', ['$scope','nguserservice', function($scope, nguserservice){ // call user , set scope variable nguserservice.getuser(function(user){$scope.currentuser = user;}); }]); })();
Comments
Post a Comment