Phoenix Phoenix - 2 months ago 14
AngularJS Question

How to handle $rootscope and take user id of logged in user in AngularJS?

I want to find the ID of the logged in user and display it in a page. I am new to angular and I don't have much clue on how to handle a session..

I have an angular app which is connected to backend API (.net core).

I will show the instances where $rootScope is used in the website (login and authorization is already enabled). I need to get an understanding of this to learn the app.

In App.js :

//Run phase
myApp.run(function($rootScope, $state) {
$rootScope.$state = $state; //Get state info in view

//Should below code be using rootScope or localStorage.. Check which one is better and why.

if (window.sessionStorage["userInfo"]) {

$rootScope.userInfo = JSON.parse(window.sessionStorage["userInfo"]);
}

//Check session and redirect to specific page
$rootScope.$on('$stateChangeStart', function(event, toState, toParams, fromState, fromParams){
if(toState && toState.data && toState.data.auth && !window.sessionStorage["userInfo"]){
event.preventDefault();
window.location.href = "#login";
}

if(!toState && !toState.data && !toState.data.auth && window.sessionStorage["userInfo"]){
event.preventDefault();
window.location.href = "#dashboard";
}
});


});


Users.js :

'use strict';
angular.module('users', []);

//Routers
myApp.config(function($stateProvider) {

//Login
$stateProvider.state('login', {
url: "/login",
templateUrl: 'partials/users/login.html',
controller: 'loginController'
});
//Factories
myApp.factory('userServices', ['$http', function($http) {

var factoryDefinitions = {
login: function (loginReq) {
$http.defaults.headers.common['Access-Control-Allow-Origin'] = '*';
return $http.post('http://localhost:1783/api/token?UserName='+loginReq.username+'&password='+loginReq.password).success(function (data) { return data; });
}
}

return factoryDefinitions;
}
]);

//Controllers
myApp.controller('loginController', ['$scope', 'userServices', '$location', '$rootScope', function($scope, userServices, $location, $rootScope) {

$scope.doLogin = function() {

if ($scope.loginForm.$valid) {
userServices.login($scope.login).then(function(result){
$scope.data = result;
if (!result.error) {
window.sessionStorage["userInfo"] = JSON.stringify(result.data);
$rootScope.userInfo = JSON.parse(window.sessionStorage["userInfo"]);
//$localStorage.currentUser = { username: login.username, token: result.data };
//$http.defaults.headers.common.Authorization = 'Token ' + response.token;
$location.path("/dashboard");
}
});
}
};
}]);


I came to know that the information about the user will be available in $rootScope.userInfo. If so, how can I take a value inside it?

Please explain with an example if possible. Thanks in advance.

Answer

One:

myApp.controller('loginController', [
'$scope', 'userServices', '$location', 
'$rootScope', 
function($scope, userServices, $location, $rootScope) {

Inside the controller, $rootScope was injected which makes you have access to the userInfo in that controller.

so if you inject $rootScope into another controller and console.log($rootScope.userInfo) you would see the users data.

myApp.controller('anotherController', ['$scope', '$rootScope', function
 ($scope, $rootScope){

    console.log($rootScope.userInfo) //you'd see the users data from sessionStorage

});

According to this post on quora

$scope is an object that is accessible from current component e.g Controller, Service only. $rootScope refers to an object which is accessible from everywhere of the application. You can think $rootScope as global variable and $scope as local variables.

$rootScope Defn.